MVC 5 BeginCollectionItem与部分CRUD [英] MVC 5 BeginCollectionItem with Partial CRUD

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

问题描述

我做了下面的问题,这仍然是相同的,但通过模型和问候我想要达到并在那里,我遇到了问题,希望能更加清晰的变化。



下面显示了两个班,公司和员工,公司有员工的列表。



这将是一个输入表单于是就有在没有任何数据和开始。



最后,我希望用户能够尽可能多的Employee对象,因为他们希望添加到公司的对象模型,并为员工对象要更新



我在正确的轨道上用BeginCollectionItem因此我可以添加/因为我想删除许多Employee对象?
当我点击添加按钮,它需要的局部视图另一页(有AjaxActionLink),但不使用JavaScript的。



更新
删除AjaxActionLink和使用的JavaScript来代替。



首页

  @model MvcTest.Models.Company 
@ {
ViewBag.Title =指数;
布局=〜/查看/共享/ _Layout.cshtml
}

< H2>公司< / H>
< D​​IV>
@ Html.LabelFor(M = GT; m.Name)
@ Html.EditorFor(M = GT; m.Name)
< / DIV>
<&字段集GT;
<传奇>员工与LT; /传说>
< D​​IV ID =新员工>
@foreach(在Model.Employees VAR员工)
{
Html.RenderPartial(_员工,员工);
}
< / DIV>
< D​​IV>
<输入类型=按钮ID =addemployeeNAME =addemployeeVALUE =添加员工/>
< BR />
< / DIV>
< BR />
@section脚本
{
<脚本类型=文/ JavaScript的>
$('#addemployee')上('点击',功能(){
$阿贾克斯({
异步:假,
网址:'/公司/ AddNewEmployee '
})成功(功能(partialView){
$('#新员工')追加(partialView);
});
});
< / SCRIPT>
}
< /字段集>
< D​​IV>
<输入类型=提交值=提交/>
< / DIV>



_员工职业PartialView



  @model MvcTest.Models.Employee 

@using(Html.BeginCollectionItem(员工))
{
< DIV CLASS =employeeRow>
@ Html.LabelFor(M = GT; m.Name)
@ Html.EditorFor(M = GT; m.Name)

@ Html.LabelFor(M = GT ; m.Telephone)
@ Html.EditorFor(M = GT; m.Telephone)

@ Html.LabelFor(M = GT; m.Mobile)
@Html。 EditorFor(M = GT; m.Mobile)

@ Html.LabelFor(M = GT; m.JobTitle)
@ Html.EditorFor(M = GT; m.JobTitle)

< A HREF =#类=deleteRow>删除< / A>
< / DIV>
}

@section脚本
{
$(a.deleteRow)。生活(点击,函数(){
$( 。这一点)。家长(div.employeeRow:第一),删除();
返回false;
});
}



控制器



 公共类CompanyController:控制器
{
// GET:公司
公众的ActionResult指数()
$ { b $ b变种newCompany =新公司();
返回查看(newCompany);
}
公众的ActionResult AddNewEmployee()
{
变种员工=新员工();
返回PartialView(_员工,员工);
}
}



型号

 公共类公司
{
[关键]
公众诠释标识{搞定;组; }
[显示(名称=公司)]
公共字符串名称{;组; }
公开名单<员工>员工{搞定;组; }

//公众公司()
// {
//员工=新的List<员工>
// {
//新员工{名称=输入名称}
//};
//}
}
公共类员工
{
[关键]
公众诠释标识{搞定;组; }
[显示(NAME =雇员)]
公共字符串名称{;组; }
公共字符串电话{搞定;组; }
公共字符串移动{获取;设置;}
[显示(NAME =职位)]
公共字符串JOBTITLE {获取;设置;}
}


解决方案

您不需要使用BeginCollectionItem,以实现这一目标。不必考虑它自己,并试图将其用于类似的问题,看起来它是这种性质与早期版本的MVC的问题产生。



使用部分视图来显示和更新列表。一局部视图,以显示与通过对象的列表遍历,另一个以创建新的对象,在交回更新列表将显示与列表中的局部视图新创建的对象



我贴在这里了类似的问题应该解决您的问题,点击这里



希望这有助于。



更新
你删除不工作的原因是因为你不能从局部视图调用JS,把它放在主视图(@section脚本)。 。此外,我觉得你有一点在你的div的class和id的关键字糊涂,看看下面



所以,你应该有:



管窥

  @model MvcTest.Models.Employee 
@using(Html.BeginCollectionItem(员工))
{
< D​​IV ID =employeeRow级=employeeRow>
@ Html.LabelFor(M = GT; m.Name)
@ Html.EditorFor(M = GT; m.Name)

@ Html.LabelFor(M = GT ; m.Telephone)
@ Html.EditorFor(M = GT; m.Telephone)

@ Html.LabelFor(M = GT; m.Mobile)
@Html。 EditorFor(M = GT; m.Mobile)

@ Html.LabelFor(M = GT; m.JobTitle)
@ Html.EditorFor(M = GT; m.JobTitle)

< A HREF =#ID =deleteRow级=deleteRow的onclick =deleteFunction()>删除< / A>
< / DIV>
}

主要查看



  @model MvcTest.Models.Company 
@ {
ViewBag.Title =指数;
布局=〜/查看/共享/ _Layout.cshtml
}

< H2>公司< / H>
< D​​IV>
@ Html.LabelFor(M = GT; m.Name)
@ Html.EditorFor(M = GT; m.Name)
< / DIV>
<&字段集GT;
<传奇>员工与LT; /传说>
< D​​IV ID =新员工>
@foreach(在Model.Employees VAR员工)
{
Html.RenderPartial(_员工,员工);
}
< / DIV>
< D​​IV>
<输入类型=按钮ID =addemployeeNAME =addemployeeVALUE =添加员工/>
< BR />
< / DIV>
< BR />
@section脚本
{
<脚本类型=文/ JavaScript的>
$('#addemployee')上('点击',功能(){
$阿贾克斯({
异步:假,
网址:'/公司/ AddNewEmployee '
})成功(功能(partialView){
$('#新员工')追加(partialView);
});
});

$(#deleteRow),生活(点击,函数(){
$(本)。家长(#employeeRow:第一),删除(); $。 b $ b返回FALSE;
});
< / SCRIPT>
}
< /字段集>
< D​​IV>
<输入类型=提交值=提交/>
< / DIV>


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>

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆