MVC 5 BeginCollectionItem with Partial CRUD

后端 未结 4 1354
夕颜
夕颜 2020-11-30 04:10

I have made changes below to the question, which is still the same but hopefully a lot clearer through the models and in regards to what I want to achieve and where I\'ve co

4条回答
  •  隐瞒了意图╮
    2020-11-30 05:04

    You do not need to use BeginCollectionItem in order to achieve this. From having to look into it myself and trying to use it for a similar issue, it appears it was created for problems of this nature with earlier versions of MVC.

    Use Partial Views to display and update the list. One partial view to display and iterate through the list of objects, and another to create a new object which upon post back to update the list will show the newly created object in the partial view with the list.

    I posted a similar question on here which should solve your issue, click here

    Hope this helps.

    Update The reason your delete doesn't work is because you can't call JS from Partial View, put it in the main view (@section Script). Also I think you got a bit muddled with your class and id keywords in your divs, have a look below.

    So you should have:

    Partial View

    @model MvcTest.Models.Employee
        @using (Html.BeginCollectionItem("Employees"))
        {
            
    @Html.LabelFor(m => m.Name) @Html.EditorFor(m => m.Name) @Html.LabelFor(m => m.Telephone) @Html.EditorFor(m => m.Telephone) @Html.LabelFor(m => m.Mobile) @Html.EditorFor(m => m.Mobile) @Html.LabelFor(m => m.JobTitle) @Html.EditorFor(m => m.JobTitle) Delete
    }

    Main View

        @model MvcTest.Models.Company
    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    

    Company

    @Html.LabelFor(m => m.Name) @Html.EditorFor(m => m.Name)
    Employees
    @foreach (var Employee in Model.Employees) { Html.RenderPartial("_Employee", Employee); }


    @section Scripts { }

提交回复
热议问题