主要的RegisterModel调用嵌套的HomeAddress和MailAddress模型。
public class RegisterModel
{
Public string FirstName {get; set;}
Public string LastName {get; set;}
Public HomeAddressModel homeAddress {get; set;}
Public MailAddressModel mailAddress {get; set;}
}
public class HomeAddressModel
{
Public string Street1 {get; set;}
Public string Street2 {get; set;}
Public string State {get; set;}
Public string City {get; set;}
}
public class MailAddressModel
{
Public string Street1 {get; set;}
Public string Street2 {get; set;}
Public string State {get; set;}
Public string City {get; set;}
}
地址的部分视图
@model MyNamespace.Models.???
@{
Layout = "~/Views/_Layout.cshtml";
}
<div id="Address">
//Street1
//Street2
//State
//City
</div>
如何定义我的Parital视图,以便我可以在运行时使用HomeAddressModel或MailAddressModel绑定它。
我的主要注册视图
@model MyNamespace.Models.RegisterModel
@{
Layout = "~/Views/_Layout.cshtml";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
@Html.TextBoxFor("FirstName");
@Html.TextBoxFor("LastName");
//Render Partial View for HomeAddress.
//Will provide a checkbox if Mailing Address is different.
//Render Partial View for MailAddress.
</div>
}
public ActionResult Register()
{
var model = new RegsiterModel();
return View(model);
}
[HttpPost]
public ActionResult Register(RegisterModel model,
HomeAddressModel homeAddress,
MailAddressModel mailingAddress)
{
//Do Something with different Addresses
return View();
}
这个问题有5个部分: -
答案 0 :(得分:1)
有一个地址模型,如
public class AddressModel
{
Public string Street1 {get; set;}
Public string Street2 {get; set;}
Public string State {get; set;}
Public string City {get; set;}
}
在Views / Shared / EditorTemplates / AddressModel.cshtml中为它制作局部视图
@model MyNamespace.Models.AddressModel
<div id="Address">
Html.TextBoxFor(m => m.Street1)
//Street2
//State
//City
</div>
现在,如果您有视图模型
public class RegisterModel
{
Public string FirstName {get; set;}
Public string LastName {get; set;}
Public AddressModel HomeAddress {get; set;}
Public AddressModel MailAddress {get; set;}
}
简单地为每个地址渲染部分视图,如下所示
<div id="form">
@Html.TextBoxFor(m => m.FirstName);
@Html.TextBoxFor(m => m.LastName);
@Html.EditorFor(m => m.HomeAddress) // !! -> this will render AdressModel.cshtml as a partial view, and will pass HomeAdress to it
//Will provide a checkbox if Mailing Address is different.
@Html.EditorFor(m => m.MailAddress)
</div>
如果您需要更多逻辑(视图的附加参数或类似内容),您可以选择将对EditorFor的调用包装到您自己的帮助器方法中
在HttpPost方法中使用此
[HttpPost]
public ActionResult Register(RegisterModel model)
{
}
并且地址将绑定到RegisterModel的属性。