开发者

Binding View Model from a form post with inner complex types

Ok, i got a viewmodel as follows:

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

    public PageViewModel
    { }

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

I use a form to edit this Item using a route like: /Controller/Edit/43

The controller uses this code:

    [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);
    }

What I want to achieve is the ID of the property: item.Item.ID to be bound to the ID from the (route)URL. However I can't get it to work. I tried using [Bind()] attribute.

I fixed it now using a hidden field in the form like so:

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

Howeve开发者_JAVA技巧r this feels a bit icky. I'd like to know if there is a better cleaner way of doing this?


Personally I would set the ID parameter in the form declaration as follows:

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

...

<% } %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜