How can I bind nested ViewModels from View to Controller in MVC3?

前端 未结 1 1866
后悔当初
后悔当初 2020-12-02 11:16

I am developing an ASP.NET MVC 3 application in C# and I use Razor. I am now dealing with a problem concerning the binding of objects through ViewModels passed/received to/f

相关标签:
1条回答
  • 2020-12-02 11:58

    Don't write loops in a view. Use editor templates:

    <strong>@Model.ContainerName</strong>
    @using (Html.BeginForm()) 
    {
        <fieldset>
            @Html.EditorFor(x => x.ItemData)
            <input type="submit" value="Save" />
        </fieldset>
    }
    

    and inside the corresponding editor template (~/Views/Shared/EditorTemplates/ItemPostModel.cshtml):

    @model ItemPostModel
    @Html.TextBox(x => x.ItemId)
    @Html.TextBox(x => x.ItemName)
    @Html.TextBox(x => x.ItemValue)
    

    And in the controller action you might need to specify the prefix:

    [HttpPost]
    public ActionResult UpdateItems(
        int containerId, 
        [Bind(Prefix = "ItemData")]ItemPostModel itemData
    )
    {
       //store itemData into repository
    }
    

    and that should be pretty much all. The editor template will take care of generating the proper input field names for the binding to work.

    0 讨论(0)
提交回复
热议问题