Saving multiple objects from MVC view

后端 未结 3 2001
失恋的感觉
失恋的感觉 2020-12-17 05:58

I\'m writing my first MVC3 application which is a simple order tracking application. I would like to edit the order and the details at the same time. When I edit the order t

3条回答
  •  被撕碎了的回忆
    2020-12-17 06:03

    The issue that you are facing is related to the names generated by the ICollection controls. Here is a detailed discussion by Phil Haack and a solution by him (in terms of an @Html extension method; download the sample project from the link given at the end of his blog post). This post targets MVC/MVC2; however it is still applicable with MVC3.

    Alternatively if you don't want to follow the hack, you can opt for a EditorTemplate for your OrderLine entity model.

    Here are the steps.

    1) Create Editor template under (Views ->Shared -> EditorTemplates -> OrderLine.cshtml) It is important to create a folder named EditorTemplates under Shared, and the template name should be same as the EntityModel for which you want to create the templete; hence the name OrderLine.cshtml)

    enter image description here

    2) Code for OrderLine.cshtml

    @model OrderTracker.Models.OrderLine
    @{
        Layout = null;
    }
    
    
    @Html.HiddenFor(modelItem => Model.id)
    
    
        @Html.EditorFor(modelItem => Model.Description)
     
    
        @Html.EditorFor(modelItem => Model.Quantity)
     
    
        @Html.EditorFor(modelItem => Model.Weight)
     
    
        @Html.EditorFor(modelItem => Model.Price)
    
    
    

    3) Edit your View with this code (note that I've used EditorFor for OrderLines collection)

    @model OrderTracker.Models.Order
    
    @{
        ViewBag.Title = "Edit";
    }
    
    

    Edit

    @using (Html.BeginForm()) {
    Order @Html.HiddenFor(model => model.ID) @Html.HiddenFor(model => model.UserId)
    @Html.LabelFor(model => model.OrderDate)
    @Html.EditorFor(model => model.OrderDate)
    @Html.LabelFor(model => model.Description)
    @Html.EditorFor(model => model.Description)
    @Html.EditorFor(model => model.OrderLines)
    Description Quantity Weight Price

    }

    4) Now on post back you will see the values

    enter image description here

提交回复
热议问题