【问题标题】:Binding View Model from a form post with inner complex types从具有内部复杂类型的表单帖子中绑定视图模型
【发布时间】:2011-02-08 06:17:55
【问题描述】:

好的,我得到了如下视图模型:

public class PageViewModel
{
    public Item Item { get; set; }
...

    public PageViewModel
    { }

    public PageViewModel(Item itemWebPage)
    {
    ...
    }
}

我使用表单来编辑此项目,使用如下路线: /控制器/编辑/43

控制器使用此代码:

    [AcceptVerbs("GET")]
    public new ActionResult Edit(int id)
    {
    ...
        PageViewModel pageViewModel = new PageViewModel(...);

        return PartialView(pageViewModel);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, PageViewModel item)
    {
        if (ModelState.IsValid)
        {
    ...
    // Here, the item.Item.ID is null, I want it to map to the id of the route.
        }

        return PartialView("Edit", item);
    }

我想要实现的是属性的 ID:item.Item.ID 绑定到来自(路由)URL 的 ID。但是我无法让它工作。我尝试使用 [Bind()] 属性。

我现在使用如下形式的隐藏字段修复它:

<%= Html.HiddenFor(model => model.Item.ID)%>

但是这感觉有点恶心。我想知道是否有更好的清洁方法?

【问题讨论】:

    标签: asp.net binding asp.net-mvc-2 viewmodel


    【解决方案1】:

    我个人会在表单声明中设置ID参数如下:

    <% using (Html.BeginForm("Edit", "YourController", FormMethod.Post, new { id = model.Item.ID })) { %>
    
    ...
    
    <% } %>
    

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 2012-07-25
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多