BeginCollectionItem内的部分行为不正确的部分 [英] BeginCollectionItem partial within partial not behaving correctly

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

问题描述

我想通过表单提交的MVC 5一次我所有的模型数据绑定使用BeginCollectionItem的一个编辑的版本在乔·史蒂芬的博客的此处

该模型,公司,有一个名单,其中,Pa_Ipv4> ,类 Pa_Ipv4 又将有一个名单,其中,IpAllocation> ,我想访问,并保存到数据库中的 IpAllocation的所有属性中的每个 Pa_Ipv4

IE浏览器: Model.pa_ipv4s [X] .requestedIps [X] .subnet

在主页使用模式公司,其中有一个部分接受 Pa_Ipv4 ,其中有一个部分接受 IpAllocation

问题1:在我的控制,我设置的第一个项目一个字符串属性列表(requestedIp),但是当我提出和回传,属性( allocationType )为空,这个属性必须是硬codeD,因为它是为DB内部使用 - 这是为什么被重置

原因:的属性是不是在POST方法,因为这样的东西最初宣布被丢弃,因为它不是结束后在

可能的解决方法:在表单中使用隐藏属性,以便它是当表单张贴present,用户无法访问属性

问2: BeginCollectionItem适当命名的属性,例如: <$c$c>pa_ipv4s[8e075d50-a5fb-436f-9cef-85abfb6910e3].requestedIps[b693b83c-b6b1-4c42-b983-4d058e766d4c].subnet,但只有最初的模型,它则忽略创建的任何人,我做了什么错?

<强>原因:需要由Pa_Ipv4部分BeginCollectionItem不能由IpAllocation BeginCollectionItem被访问,因为这些仅在初始内容产生的preFIX的GUID具有正确prefixes,任何添加以下忽略了必要的preFIX。

另一个潜在的解决方案是基本相同的概念,但使用一个div代替,使用的HTML数据属性,而不是这样,它的访问。

我觉得这两个我遇到的问题做了我如何设置我的控制器,但我已经包括了意见和示范以下为好。该模型包含的所有属性,大量的这些都已经在我的观点中删除,以节省空间,因为它们不导致该问题。

创建

  @model公司

@ {
    布局=〜/查看/共享/ _Layout.cshtml;
}
@using(Html.BeginForm())
{
    &LT; D​​IV CLASS =jumboservice&GT;
        &LT; D​​IV数据角色=页面&GT;
            &LT; D​​IV数据角色=头&GT;
                &LT; H2&GT; PA IPv4的申请表和LT; / H&GT;
            &LT; / DIV&GT;
            &LT; D​​IV CLASS =UI内容数据角色=主&GT;
                &LT; H3&GT;公司信息&LT; / H3&GT;
                &LT; D​​IV CLASS =UI网-C的UI响应&GT;
                    &LT; D​​IV CLASS =UI-块一个&GT;
                        &其中,P类=lblStyle&GT;公司名称&LT; / P&GT;
                        &LT;跨度&GT;
                            @ Html.EditorFor(M =&GT; m.name)
                            @ Html.ValidationMessageFor(M =&GT; m.name)
                        &LT; / SPAN&GT;
                    &LT; / DIV&GT;
                &LT; / DIV&GT;
            &LT; / DIV&GT;
            &LT; BR /&GT;
                @foreach(VAR我在Model.pa_ipv4s)
                {
                    @ Html.Partial(Pa_IPv4View,I)
                }
            &LT; BR /&GT;
            &LT; D​​IV数据角色=主类=UI内容&GT;
                &LT; D​​IV数据角色=controlgroup数据类型=横向&GT;
                    &LT;输入类型=提交级=UI-BTN值=创建/&GT;
                &LT; / DIV&GT;
            &LT; / DIV&GT;
        &LT; / DIV&GT;
    &LT; / DIV&GT;
}
&LT;脚本类型=文/ JavaScript的&GT;
    $(函数(){
            $('#addItemRIpM')。在('点击',函数(){
                $阿贾克斯({
                    网址:@ Url.Action(RequestedManager),
                    缓存:假的,
                    成功:函数(HTML){$(#editorRowsRIpM)追加(HTML); }
                });
                返回false;
            });
            $('#editorRowsRIpM')。在('点击','.deleteRow',函数(){
                $(本).closest('editorRow。)删除()。
            });
        });
&LT; / SCRIPT&GT;
 

Pa_Ipv4部分

  @model Pa_Ipv4

    @using(HtmlHelpers.BeginCollectionItem.Html prefixScopeExtensions.BeginCollectionItem(HTML,pa_ipv4s))
{
    @ Html.AntiForgeryToken()
    &LT; D​​IV CLASS =UI网-C的UI响应&GT;
        &LT; D​​IV CLASS =UI-块一个&GT;
            &其中,P类=lblStyle&GT;子网&LT; / P&GT;
        &LT; / DIV&GT;
        &LT; D​​IV CLASS =UI块-B&GT;
            &其中,P类=lblStyle&GT;尺寸(CIDR)&LT; / P&GT;
        &LT; / DIV&GT;
        &LT; D​​IV CLASS =UI块-C&GT;
            &其中,P类=lblStyle&GT;面膜&LT; / P&GT;
        &LT; / DIV&GT;
        &LT; D​​IV CLASS =UI块-D&GT;
        &LT; / DIV&GT;
    &LT; / DIV&GT;
    @ *请求的IP地址空间列表* @
    &LT; D​​IV ID =editorRowsRIpM&GT;
        @foreach(在Model.requestedIps VAR项)
        {
            @ Html.Partial(RequestedIpView,项目)
        }
    &LT; / DIV&GT;
    @ Html.ActionLink(添加,RequestedManager,空,新的{ID =addItemRIpM,@class =键})
}
 

RequestedIp部分

  @model IpAllocation

&LT; D​​IV CLASS =editorRow&GT;
    @using(HtmlHelpers.BeginCollectionItem.Html prefixScopeExtensions.BeginCollectionItem(HTML,requestedIps))
    {
        &LT; D​​IV CLASS =UI网-C的UI响应&GT;
            &LT; D​​IV CLASS =UI-块一个&GT;
                &LT;跨度&GT;
                    @ Html.TextBoxFor(M =&GT; m.subnet)
                &LT; / SPAN&GT;
            &LT; / DIV&GT;
            &LT; D​​IV CLASS =UI块-B&GT;
                &LT;跨度&GT;
                    @ Html.TextBoxFor(M =&GT; m.cidr)
                &LT; / SPAN&GT;
            &LT; / DIV&GT;
            &LT; D​​IV CLASS =UI块-C&GT;
                &LT;跨度&GT;
                    @ Html.TextBoxFor(M =&GT; m.mask)
                    &LT;跨度类=dltBtn&GT;
                        &LT; A HREF =#级=deleteRow&GT;删除&LT; / A&GT;
                    &LT; / SPAN&GT;
                &LT; / SPAN&GT;
            &LT; / DIV&GT;
        &LT; / DIV&GT;
    }
&LT; / DIV&GT;
 

控制器

 公众的ActionResult创建()
        {
            VAR CMP =新公司();
            cmp.contacts =新的名单,其中,联系与GT;
            {
                新的联系{EMAIL =,名称=,电话=}
            };
            cmp.pa_ipv4s =新的名单,其中,Pa_Ipv4&GT;
            {
                新Pa_Ipv4
                {
                    X最多=Pa_IPv4,registedAddress =假,existingNotes =,
                    numberOfAddresses = 0,returnedAddressSpace =假,additionalInformation =,
                    requestedIps =新的名单,其中,IpAllocation&GT;
                    {
                        新IpAllocation {allocationType =请,CIDR =,面具=,子网=} // allocationType是CMP空在创建[HttpPost]
                    }
                }
            };

            返回查看(CMP);
        }

        公众的ActionResult Pa_IPv4Manager()
        {
            返回PartialView(Pa_IPv4View,新Pa_Ipv4());
        }
        公众的ActionResult RequestedManager()
        {
            返回PartialView(RequestedIpView,新IpAllocation {allocationType =请}); // allocationType是空的CMP中创建[HttpPost]
        }

        //邮编:Pa_Ipv4 /创建
        [HttpPost]
        [ValidateAntiForgeryToken]
        公众的ActionResult创建(公司CMP)//只有一个requestedIps算,无论有多少加
        {
            如果(ModelState.IsValid)
            {
                db.companys.Add(CMP);
                db.SaveChanges();
                返回RedirectToAction(指数);
            }
 

型号

  [表(Ipv_Base)
公共类Ipv_Base
{
    [键]
    公众诠释ipv_baseId {获得;组; }
    公众诠释companyId {获得;组; }
    [ForeignKey的(companyId)]
    上市公司公司{获得;组; }
    公共字符串X最多{获得;组; }
    [需要]
    公共BOOL registedAddress {获得;组; }
    [需要]
    [数据类型(DataType.MultilineText)
    公共字符串existingNotes {获得;组; }
    [需要]
    公众诠释numberOfAddresses {获得;组; }
    [需要]
    公共BOOL returnedAddressSpace {获得;组; }
    [数据类型(DataType.MultilineText)
    公共字符串additionalInformation {获得;组; }
    //导航属性
    公共虚拟IList的&LT; IpAllocation&GT; requestedIps {获得;组; }
}
[表(「本公司」)
公共类公司
{
    [键]
    公众诠释companyId {获得;组; }
    [需要]
    公共字符串名称{;组; }
    [需要]
    公共字符串电话{获得;组; }
    [需要]
    公共字符串regNumber {获得;组; }
    //导航属性来跟踪模型属于公司
    公共虚拟IList的&LT; Pa_Ipv4&GT; pa_ipv4s {获得;组; }

}
[表(IpAllocation)]
公共类IpAllocation
{
    [键]
    公众诠释ipAllocationId {获得;组; }
    公众诠释ipv_BaseId {获得;组; }
    [ForeignKey的(ipv_BaseId)]
    公共Ipv_Base ipv_Base {获得;组; }
    [需要]
    公共字符串allocationType {获得;组; }
    [需要]
    公共字符串子网{获得;组; }
    [需要]
    公共字符串CIDR {获得;组; }
    [需要]
    公共字符串面具{获得;组; }
}
公共类Pa_Ipv4:Ipv_Base
{
    公共Pa_Ipv4()
    {
        X最多=pa_ipv4;
    }
}
 

解决方案

问题1解决方法:

第一季的问题是,该属性值,我分配在控制器没有被解析的形式回发,因为属性是不存在。

添加一个隐藏字段的属性整顿讨厌空。

 &LT; D​​IV CLASS =UI-块一个&GT;
                &LT;跨度&GT;
                    @ Html.HiddenFor(M =&GT; m.allocationType)
                    @ Html.TextBoxFor(M =&GT; m.subnet,新{@class =checkFiller})
                &LT; / SPAN&GT;
            &LT; / DIV&GT;
 

问题2解决方法:

附着的preFIX第二个模型,我面临的第一个模型的GUID的问题,主要是因为使用AJAX到控制器的操作方法我是如何发送数据。

下面显示的code段修正这些问题,并显示正确绑定的GUID。

<$c$c>name="pa_ipv4s[f7d8d024-5bb6-451d-87e3-fd3e3b8c1bba].requestedIps[d5c08a43-f65e-46d1-b224-148225599edc].subnet"现在正显示在动态创建的模型的属性,不只是最初创建

在调试在Visual Studio中运行,将鼠标悬停在模型时,挖下到的数据显示模型列表的正确计数。

控制器ActionMethod:

 公众的ActionResult ExistingManager(字符串容器preFIX)
        {
            计算机[集装箱preFIX] =容器preFIX;
            返回PartialView(ExistingIpView,新IpAllocation {allocationType =现有});
        }
 

AJAX GET方法调用控制器ActionMethod:

  $('#addItemEIpM')。在('点击',函数(){
            $阿贾克斯({
                网址:@ Url.Action(ExistingManager),
                缓存:假的,
                数据:'货柜preFIX ='+ $('#addItemEIpM)的数据(容器preFIX')。
                成功:函数(HTML){
                    $(#editorRowsEIpM)追加(HTML)。
                }
            });
            返回false;
        });
 

I am trying to bind all my model data at once through a form submission in MVC 5 using an edited version of BeginCollectionItem as discussed in Joe Steven's blog here.

The model, Company, has a List<Pa_Ipv4>, the class Pa_Ipv4 in turn has a List<IpAllocation>, I want to access and save to the database all the properties of the IpAllocation in each Pa_Ipv4.

IE: Model.pa_ipv4s[x].requestedIps[x].subnet

The main page is using model Company, which has a partial accepting Pa_Ipv4, which has a partial accepting IpAllocation.

Question 1: In my controller, I'm setting a string property for the first item in the list (requestedIp), but when I submit and postback, the property (allocationType) is null, this property needs to be hard coded as it's for internal use within the DB - why is this being reset?

Reason: The property isn't in the post method, as such what is initially declared is discarded as it's not within the end post.

Possible Solution: Use a hidden property within the form so that it is present when the form is posted and the user cannot access the property.

Question 2: BeginCollectionItem is naming attributes appropriately, IE: pa_ipv4s[8e075d50-a5fb-436f-9cef-85abfb6910e3].requestedIps[b693b83c-b6b1-4c42-b983-4d058e766d4c].subnet, but only the initial model, it's then ignoring any others created, what have I done wrong?

Reason: The GUID needed for a prefix generated by the Pa_Ipv4 sections BeginCollectionItem is not able to be accessed by the IpAllocation BeginCollectionItem, as such only the initial content has the correct prefixes, anything added hereafter misses the necessary prefix.

Another potential solution is essentially the same concept, but instead of using a div, use html data attribute instead so that it's accessible.

I think both of the issues I'm experiencing are to do with how I've set my controller up, but I've included the Views and Model below as well. The model contains all the properties, lots of these have been removed in my views to save space as these are not causing the issue.

Create

@model Company

@{
    Layout = "~/Views/Shared/_Layout.cshtml";   
}
@using (Html.BeginForm())
{
    <div class="jumboservice">
        <div data-role="page">
            <div data-role="header">
                <h2>PA IPv4 Request Form</h2>
            </div>
            <div class="ui-content" data-role="main">
                <h3>Company Details</h3>
                <div class="ui-grid-c ui-responsive">
                    <div class="ui-block-a">
                        <p class="lblStyle">Company Name</p>
                        <span>
                            @Html.EditorFor(m => m.name)
                            @Html.ValidationMessageFor(m => m.name)
                        </span>
                    </div>
                </div>
            </div>
            <br />
                @foreach (var i in Model.pa_ipv4s)
                {
                    @Html.Partial("Pa_IPv4View", i)
                }
            <br />
            <div data-role="main" class="ui-content">
                <div data-role="controlgroup" data-type="horizontal">
                    <input type="submit" class="ui-btn" value="Create" />
                </div>
            </div>
        </div>
    </div>
}
<script type="text/javascript">
    $(function () {
            $('#addItemRIpM').on('click', function () {
                $.ajax({
                    url: '@Url.Action("RequestedManager")',
                    cache: false,
                    success: function (html) { $("#editorRowsRIpM").append(html); }
                });
                return false;
            });
            $('#editorRowsRIpM').on('click', '.deleteRow', function () {
                $(this).closest('.editorRow').remove();
            });
        });
</script>

Pa_Ipv4 Partial

@model Pa_Ipv4

    @using (HtmlHelpers.BeginCollectionItem.HtmlPrefixScopeExtensions.BeginCollectionItem(Html,"pa_ipv4s"))
{
    @Html.AntiForgeryToken()
    <div class="ui-grid-c ui-responsive">
        <div class="ui-block-a">
            <p class="lblStyle">Subnet</p>
        </div>
        <div class="ui-block-b">
            <p class="lblStyle">Size(CIDR)</p>
        </div>
        <div class="ui-block-c">
            <p class="lblStyle">Mask</p>
        </div>
        <div class="ui-block-d">
        </div>
    </div>
    @*Request IP Address Space List*@
    <div id="editorRowsRIpM">
        @foreach (var item in Model.requestedIps)
        {
            @Html.Partial("RequestedIpView", item)
        }
    </div>
    @Html.ActionLink("Add", "RequestedManager", null, new { id = "addItemRIpM", @class = "button" })
}

RequestedIp Partial

@model IpAllocation

<div class="editorRow">
    @using (HtmlHelpers.BeginCollectionItem.HtmlPrefixScopeExtensions.BeginCollectionItem(Html, "requestedIps"))
    {
        <div class="ui-grid-c ui-responsive">
            <div class="ui-block-a">
                <span>
                    @Html.TextBoxFor(m => m.subnet)
                </span>
            </div>
            <div class="ui-block-b">
                <span>
                    @Html.TextBoxFor(m => m.cidr)
                </span>
            </div>
            <div class="ui-block-c">
                <span>
                    @Html.TextBoxFor(m => m.mask)
                    <span class="dltBtn">
                        <a href="#" class="deleteRow">Remove</a>
                    </span>
                </span>
            </div>
        </div>
    }
</div>

Controller

public ActionResult Create()
        {
            var cmp = new Company();
            cmp.contacts = new List<Contact>
            {
                new Contact { email = "", name = "", telephone = "" }
            };
            cmp.pa_ipv4s = new List<Pa_Ipv4>
            {
                new Pa_Ipv4
                { 
                    ipType = "Pa_IPv4", registedAddress = false, existingNotes = "",
                    numberOfAddresses = 0, returnedAddressSpace = false, additionalInformation = "",
                    requestedIps = new List<IpAllocation>
                    {
                        new IpAllocation { allocationType = "Requested", cidr = "", mask = "", subnet  = "" } // allocationType is null in cmp in the Create[HttpPost]
                    }
                }
            };

            return View(cmp);
        }

        public ActionResult Pa_IPv4Manager()
        {
            return PartialView("Pa_IPv4View", new Pa_Ipv4());
        }
        public ActionResult RequestedManager()
        {
            return PartialView("RequestedIpView", new IpAllocation { allocationType = "Requested" }); // allocationType is null in cmp in the Create[HttpPost]
        }

        // POST: Pa_Ipv4/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Company cmp) //only one requestedIps count regardless of how many add
        {
            if (ModelState.IsValid)
            {
                db.companys.Add(cmp);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

Model

[Table("Ipv_Base")]
public class Ipv_Base
{
    [Key]
    public int ipv_baseId { get; set; }
    public int companyId { get; set; }
    [ForeignKey("companyId")]
    public Company company { get; set; }
    public string ipType { get; set; }
    [Required]
    public bool registedAddress { get; set; }
    [Required]
    [DataType(DataType.MultilineText)]
    public string existingNotes { get; set; }
    [Required]
    public int numberOfAddresses { get; set; }
    [Required]
    public bool returnedAddressSpace { get; set; }
    [DataType(DataType.MultilineText)]
    public string additionalInformation { get; set; }
    // navigation properties
    public virtual IList<IpAllocation> requestedIps { get; set; }
}
[Table("Company")]
public class Company
{
    [Key]
    public int companyId { get; set; }
    [Required]
    public string name { get; set; }
    [Required]
    public string telephone { get; set; }
    [Required]
    public string regNumber { get; set; }
    // navigation properties to keep track of the models that belong to the company
    public virtual IList<Pa_Ipv4> pa_ipv4s { get; set; }

}
[Table("IpAllocation")]
public class IpAllocation
{
    [Key]
    public int ipAllocationId { get; set; }
    public int ipv_BaseId { get; set; }
    [ForeignKey("ipv_BaseId")]
    public Ipv_Base ipv_Base { get; set; }
    [Required]
    public string allocationType { get; set; }
    [Required]
    public string subnet { get; set; }
    [Required]
    public string cidr { get; set; }
    [Required]
    public string mask { get; set; }
}
public class Pa_Ipv4 : Ipv_Base
{
    public Pa_Ipv4()
    {
        ipType = "pa_ipv4";
    }
}

解决方案

Question 1 Solution:

The issue with Q1 was that the property value I was assigning in the controller wasn't being parsed back from the form post, because the property wasn't there.

Added a hidden field for the property to rectify the pesky null.

<div class="ui-block-a">
                <span>
                    @Html.HiddenFor(m => m.allocationType)
                    @Html.TextBoxFor(m => m.subnet, new { @class = "checkFiller" })
                </span>
            </div>

Question 2 Solution:

The issues that I was facing with the GUID of the first model being attached as the prefix to the second model was largely due to how I was sending data using AJAX to the controller action method.

The code snippets shown below fix the issues and display the correctly bound GUIDs.

name="pa_ipv4s[f7d8d024-5bb6-451d-87e3-fd3e3b8c1bba].requestedIps[d5c08a43-f65e-46d1-b224-148225599edc].subnet" is now being shown on the dynamically created model properties, not just the initially created.

When running in debug in visual studio and hovering over the model, digging down into the data shows the correct counts of the model lists.

Controller ActionMethod:

public ActionResult ExistingManager(string containerPrefix)
        {
            ViewData["ContainerPrefix"] = containerPrefix;
            return PartialView("ExistingIpView", new IpAllocation { allocationType = "Existing" });
        }

AJAX GET Method calling Controller ActionMethod:

$('#addItemEIpM').on('click', function () {
            $.ajax({
                url: '@Url.Action("ExistingManager")',
                cache: false,
                data: 'containerPrefix=' + $('#addItemEIpM').data('containerprefix'),
                success: function (html) {
                    $("#editorRowsEIpM").append(html);
                }
            });
            return false;
        });

这篇关于BeginCollectionItem内的部分行为不正确的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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