我有一个注册主视图,它显示了两种不同类型的地址 1. 家庭地址 2. 邮寄地址
public class RegisterModel
{
public AddressModel HomeAddress { get; set; }
public AddressModel MailAddress { get; set; }
}
public class AddressModel
{
public string Street1 { get; set; }
public string Street2 { get; set; }
public string State { get; set; }
public string City { get; set; }
}
我的主要注册视图强类型为 RegisterModel,如下所示
@model MyNamespace.Models.RegisterModel
@{
Layout = "~/Views/_Layout.cshtml";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
@Html.Action("MyAddressPartial")
@Html.Action("MyAddressPartial")
</div>
}
MyAddressPartialView 如下: -
@model MyNamespace.Models.AddressModel
@{
Layout = "~/Views/_Layout.cshtml";
}
<div id="Address">
@Html.TextBoxFor(m=>m.Street1 ,new { @id="Street1 "})
@Html.TextBoxFor(m=>m.Street2,new { @id="Street2"})
@Html.TextBoxFor(m=>m.State ,new { @id="State "})
@Html.TextBoxFor(m=>m.City,new { @id="City"})
</div>
我的注册控制器:-
// Have to instantiate the strongly Typed partial view when my form first loads
// and then pass it as parameter to "Register" post action method.
// As you can see the @Html.Action("MyAddressPartial") above in main
// Register View calls this.
public ActionResult MyAddressPartial()
{
return PartialView("MyAddressPartialView", new AddressModel());
}
我在同一个注册控制器中将我的主表单提交给下面提到的操作方法。
[HttpPost]
public ActionResult Register(RegisterModel model,
AddressModel homeAddress,
AddressModel mailingAddress)
{
//I want to access homeAddress and mailingAddress contents which should
//be different, but as if now it comes same.
}
我不想为 MailingAddress 和 HomeAddress 创建一个单独的类。如果我这样做,那么我将不得不为每个地址创建两个单独的强类型部分视图。
关于如何重用类和局部视图并使它们动态化并在 Action Method Post 中读取它们的单独值的任何想法。
编辑 1 对 scott-pascoe 的回复:-
在 DisplayTemplates 文件夹中,我添加了以下 AddressModel.cshtml
<div>
@Html.DisplayFor(m => m.Street1);
@Html.DisplayFor(m => m.Street2);
@Html.DisplayFor(m => m.State);
@Html.DisplayFor(m => m.City);
</div>
同样在 EditorTemplate 文件夹中,我添加了以下 AddressModel.cshtml 但使用 EditorFor
<div>
@Html.EditorFor(m => m.Street1);
@Html.EditorFor(m => m.Street2);
@Html.EditorFor(m => m.State);
@Html.EditorFor(m => m.City);
</div>
现在我如何在 RegisterView 中使用它们以及如何在 Controller 的 post Action Method 中读取值?还有什么需要修改的?我在上面添加了几乎整个代码。我是 MVC 的初学者。