带有部分 CRUD 的 MVC 5 BeginCollectionItem [英] MVC 5 BeginCollectionItem with Partial CRUD

查看:20
本文介绍了带有部分 CRUD 的 MVC 5 BeginCollectionItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对下面的问题进行了更改,这仍然是相同的,但希望通过模型和关于我想要实现的目标以及我遇到问题的地方更加清晰.

下面显示了两个类,公司和员工,公司有一个员工列表.

这将是一个输入表单,因此开始时不会有数据.

最终我希望用户能够根据需要将尽可能多的 Employee 对象添加到 Company 对象模型中,并更新 Employee 对象

我使用 BeginCollectionItem 是否走在正确的轨道上,以便我可以添加/删除任意数量的 Employee 对象?当我单击添加"按钮时,它会将它带到另一个页面上的部分视图(使用 AjaxActionLink),但不使用 JavaScript.

更新移除了 AjaxActionLink 并改用 JavaScript.

索引

@model MvcTest.Models.Company@{ViewBag.Title = "索引";布局 = "~/Views/Shared/_Layout.cshtml";}<h2>公司</h2><div>@Html.LabelFor(m => m.Name)@Html.EditorFor(m => m.Name)

<字段集><legend>员工</legend><div id="new-Employee">@foreach(Model.Employees 中的 var Employee){Html.RenderPartial("_Employee", Employee);}

<div><input type="button" id="addemployee" name="addemployee" value="添加员工"/><br/>

<br/>@section 脚本{<script type="text/javascript">$('#addemployee').on('click', function () {$.ajax({异步:假,url: '/公司/AddNewEmployee'}).成功(功能(部分视图){$('#new-Employee').append(partialView);});});}</fieldset><div><input type="submit" value="Submit"/>

_Employee PartialView

 @model MvcTest.Models.Employee@using (Html.BeginCollectionItem("Employees")){<div class="employeeRow">@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)<a href="#" class="deleteRow">删除</a>

}@section 脚本{$("a.deleteRow").live("点击", function(){$(this).parents("div.employeeRow:first").remove();返回假;});}

控制器

public class CompanyController : 控制器{//获取:公司公共 ActionResult 索引(){var newCompany = new Company();返回视图(新公司);}公共 ActionResult AddNewEmployee(){var 员工 = 新员工();return PartialView("_Employee", 员工);}}

模型

公共类公司{[钥匙]公共 int Id { 获取;放;}[显示(名称=公司")]公共字符串名称 { 获取;放;}公共列表<员工>员工{得到;放;}//上市公司()//{//员工 = 新列表<员工>//{//新员工{ Name = "输入姓名"}//};//}}公开课员工{[钥匙]公共 int Id { 获取;放;}[显示(姓名=员工")]公共字符串名称 { 获取;放;}公共字符串电话{得到;放;}公共字符串移动{get;set;}[显示(姓名=职位")]公共字符串 JobTitle {get;set;}}

解决方案

您不需要使用 BeginCollectionItem 来实现此目的.从不得不自己研究它并尝试将它用于类似的问题,它似乎是为早期版本的 MVC 的这种性质的问题而创建的.

使用局部视图来显示和更新列表.一个局部视图显示并遍历对象列表,另一个创建一个新对象,在回发更新列表时,将在局部视图中显示新创建的对象和列表.

我在这里发布了一个类似的问题,应该可以解决您的问题,单击此处

希望这会有所帮助.

更新您的删除不起作用的原因是因为您无法从 Partial View 调用 JS,将其放在主视图中(@section Script).此外,我认为您对 div 中的 class 和 id 关键字有些困惑,请看下面.

所以你应该:

部分视图

@model MvcTest.Models.Employee@using (Html.BeginCollectionItem("Employees")){<div id="employeeRow" class="employeeRow">@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)<a href="#" id="deleteRow" class="deleteRow" onclick="deleteFunction()">删除</a>

}

主视图

 @model MvcTest.Models.Company@{ViewBag.Title = "索引";布局 = "~/Views/Shared/_Layout.cshtml";}<h2>公司</h2><div>@Html.LabelFor(m => m.Name)@Html.EditorFor(m => m.Name)

<字段集><legend>员工</legend><div id="new-Employee">@foreach(Model.Employees 中的 var Employee){Html.RenderPartial("_Employee", Employee);}

<div><input type="button" id="addemployee" name="addemployee" value="添加员工"/><br/>

<br/>@section 脚本{<script type="text/javascript">$('#addemployee').on('click', function () {$.ajax({异步:假,url: '/公司/AddNewEmployee'}).成功(功能(部分视图){$('#new-Employee').append(partialView);});});$("#deleteRow").live("click", function () {$(this).parents("#employeeRow:first").remove();返回假;});}</fieldset><div><input type="submit" value="Submit"/>

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 come up against issues.

Below are shown two classes, Company and Employee, Company has a list of Employees.

This will be an input form so there will be no data in there to begin with.

Ultimately I want the user to be able to add as many Employee objects to the Company object model as they want and for the Employee objects to be updated

Am I on the right track with using BeginCollectionItem so I can add/remove as many Employee objects as I want? When I click on the Add button it takes it to the partial view on another page (with AjaxActionLink) but not with JavaScript.

Update Removed AjaxActionLink and used JavaScript instead.

Index

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

<h2>Company</h2>
<div>
    @Html.LabelFor(m => m.Name)
    @Html.EditorFor(m => m.Name)
</div>
<fieldset>
    <legend>Employees</legend>
    <div id="new-Employee">
        @foreach (var Employee in Model.Employees)
        {
            Html.RenderPartial("_Employee", Employee);
        }
    </div>
    <div>
        <input type="button" id="addemployee" name="addemployee" value="Add Employee"/>
        <br/>
    </div>
    <br/>
    @section Scripts
    {
        <script type="text/javascript">
            $('#addemployee').on('click', function () {
                $.ajax({
                    async: false,
                    url: '/Company/AddNewEmployee'
                }).success(function (partialView) {
                    $('#new-Employee').append(partialView);
                });
            });
        </script>
    }
</fieldset>
<div>
    <input type="submit" value="Submit" />
</div>

_Employee PartialView

    @model MvcTest.Models.Employee

@using (Html.BeginCollectionItem("Employees"))
{
    <div class="employeeRow">
        @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)

        <a href="#" class="deleteRow">Delete</a>
    </div>
}

@section Scripts
{
$("a.deleteRow").live("click", function(){
    $(this).parents("div.employeeRow:first").remove();
return false;
});
}

Controller

public class CompanyController : Controller
    {
        // GET: Company
        public ActionResult Index()
        {
            var newCompany = new Company();
            return View(newCompany);
        }
        public ActionResult AddNewEmployee()
        {
            var employee = new Employee();
            return PartialView("_Employee", employee);
        }
    }

Model

public class Company
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Company")]
        public string Name { get; set; }
        public List<Employee> Employees { get; set; }

        //public Company()
        //{
        //    Employees = new List<Employee>
        //    {
        //        new Employee{ Name = "Enter name"}
        //    };
        //}
    }
    public class Employee
    {
        [Key]
        public int Id { get; set; }
        [Display(Name="Employee")]
        public string Name { get; set; }
        public string Telephone { get; set; }
        public string Mobile {get;set;}
        [Display(Name="Job Title")]
        public string JobTitle {get;set;}
    }

解决方案

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"))
    {
        <div id="employeeRow" class="employeeRow">
            @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)

            <a href="#" id="deleteRow" class="deleteRow" onclick="deleteFunction()">Delete</a>
        </div>
    }

Main View

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

<h2>Company</h2>
<div>
    @Html.LabelFor(m => m.Name)
    @Html.EditorFor(m => m.Name)
</div>
<fieldset>
    <legend>Employees</legend>
    <div id="new-Employee">
        @foreach (var Employee in Model.Employees)
        {
            Html.RenderPartial("_Employee", Employee);
        }
    </div>
    <div>
        <input type="button" id="addemployee" name="addemployee" value="Add Employee"/>
        <br/>
    </div>
    <br/>
    @section Scripts
    {
        <script type="text/javascript">
            $('#addemployee').on('click', function () {
                $.ajax({
                    async: false,
                    url: '/Company/AddNewEmployee'
                }).success(function (partialView) {
                    $('#new-Employee').append(partialView);
                });
            });

            $("#deleteRow").live("click", function () {
                $(this).parents("#employeeRow:first").remove();
                return false;
            });
        </script>
    }
</fieldset>
<div>
    <input type="submit" value="Submit" />
</div>

这篇关于带有部分 CRUD 的 MVC 5 BeginCollectionItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆