【发布时间】:2013-05-06 16:34:36
【问题描述】:
主要的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 个部分:-
- RegisterModel 类创建是否正确?这是他们的方式 我们可以嵌套它们吗?
- 我们是否应该有一个地址类和 2 个不同的属性 两个地址?像 Address home {get;set;} 和 地址邮件{get;set;}。如果是,那么如何实现下一步。
- 如何为地址创建局部视图?在这两种情况下 使用单独的 HomeAddres 类和 MailAddress 类。或使用单个地址类。
- 如何使用两种方法在主寄存器视图中声明 partialView 如上所述。
- 如何确保在 [HttpPost] Action Method 中我们可以阅读所有内容 值,即 RegisterModel 值是绑定的,并且单独的地址 也被绑定。
【问题讨论】:
-
地址是否需要2种不同的模型?
-
@Necros 如果我们使用一个类,那么它不会变得更复杂吗?我尝试使用一个,但它对我来说更糟,尤其是在 [HttpPost] Action 方法中,我将如何获得 2 个不同的地址?可能是我不知道如何使用单个地址类来实现。
标签: asp.net-mvc partial-views model-binding custom-model-binder strongly-typed-view