繁体   English   中英

MVC Razor在视图中实现多个相同类型的部分并读入控制器

[英]MVC Razor Implementing multiple partials of same type in a View and read in controller

我需要一些有关如何最好地实现基于列表的部分视图并在页面上多次实现的建议。

因此,鉴于此:

<div>
 <b>Contact Name</b>
 @Html.TextBoxFor(m => m.ApplicationDetail.Name, new { @class = "formInputSmall" })@Html.ValidationMessageFor(model => model.ApplicationDetail.Name)          
 <b>Current Address</b>
   @Html.Partial("_address", Model.Address)
 <b>Previous Address</b>
    @Html.Partial("_address", Model.Address)
</div>

我有一个复杂的模型,它具有标题记录,并且可以包含多个地址。

模型页面类

public class EntityDetails
{
    public ApplicationDetail ApplictaionDetails{ get; set; }
    public List<Address> Address { get; set; }
}

部分地址

@model Application.Models.DataModels.Address
@Html.TextBoxFor(m => m.AddressLine1, new { @class = "formInputSmall" })@Html.ValidationMessageFor(model => model.AddressLine1)
@Html.TextBoxFor(m => m.AddressLine2, new { @class = "formInputSmall" })@Html.ValidationMessageFor(model => model.AddressLine2)
@Html.TextBoxFor(m => m.City, new { @class = "formInputSmall" })@Html.ValidationMessageFor(model => model.City)
@Html.TextBoxFor(m => m.Postcode, new { @class = "formInputSmall" })@Html.ValidationMessageFor(model => model.Postcode)
@Html.DropDownListFor(m => m.Country, new SelectList(ViewBag.CountryType, "ID", "Value"), "Select...", null)@Html.ValidationMessageFor(model => model.Country)

我无法弄清楚如何区分不同类型的地址,因为地址表具有不同的类型。

我可以就如何最好地实现我要实现的目标提出一些建议吗? 我不反对它被撕裂。

foreach (var address in Model.Address)
{
    @Html.Partial("_address", address)
}

这不是您所需要的吗? 地址类型不同意味着什么? 如果您的意思是当前地址与以前的地址与任何其他地址类型,那么我说您有不同的地址类型,并且需要为地址类型引入一个Enum

public Enum AddressTypes
{
    Current,
    Previous
}

然后将此Enum用作Address类中的属性,如下所示:

public class Address
{
    public AddressTypes AddressType {get; set;}
}

这样一来,您就可以在部分视图中区分不同的地址类型。

您应该为此使用EditorTemplates,而不是局部的。 EditorTemplates是专门针对此(和类似)问题而设计的。

http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx

默认情况下,部分函数不会解决许多格式化嵌套表格字段以供模型绑定程序正确读取的问题。 您可以使用Partials来做到这一点,但是您必须做额外的工作。 EditorTemplates为您解决了这一问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM