【发布时间】:2013-04-23 09:17:16
【问题描述】:
我有 NameModel 和 RegisterModel 以及 SuperClass 类如下:-
案例 1:- 使用超类
public class SuperClass
{
public RegisterModel Register{ get; set; }
public NameModel NameInfo { get; set; }
}
public class NameModel
{
[Required]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
}
public class RegisterModel
{
public NameModel NameInfo{ get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set;}
}
MyNamePartial 强类型视图如下:-
@model MyNamespace.Models.NameModel
@{
Layout = null;
}
{
@Html.TextBoxFor(m=>m.FirstName,new { @id="firstName"} )
@Html.TextBoxFor(m=>m.MiddleName,new { @id="middleName"} )
@Html.TextBoxFor(m=>m.LastName,new { @id="lastName"} )
}
我的注册视图是注册模型的强类型如下:-
@model MyNamespace.Models.SuperClass
@{
Layout = "~/Views/_Layout.cshtml";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
@Html.Partial("NameModel",Model.NameInfo)
@Html.TextBoxFor(m=>m.Register.UserName,new { @id="userName"})
@Html.TextBoxFor(m=>m.Register.Password,new { @id="password"})
<input type="submit" value="Register" id="btnRegister" />
</div>
}
上述方法会导致对象引用错误。
案例 2:- 使用 HTML.Action 而没有 SuperClass 尝试使用@Html.Action("MyNamePartialView") 而不是@Html.Partial("NameModel",Model.NameInfo),然后我使用如下控制器操作方法
我的注册视图是注册模型的强类型如下:-
@model MyNamespace.Models.RegisterModel
@{
Layout = "~/Views/_Layout.cshtml";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
@Html.Action("MyNamePartialView")
@Html.TextBoxFor(m=>m.UserName,new { @id="userName"})
@Html.TextBoxFor(m=>m.Password,new { @id="password"})
<input type="submit" value="Register" id="btnRegister" />
</div>
}
注册控制器:-
public ActionResult MyNamePartialView()
{
return PartialView("MyNamePartial", new NameModel());
}
[HttpPost]
[AllowAnonymous]
public ActionResult Register(RegisterrModel model)
{
@ViewBag.sideMenuHeader = "Create an Account";
if (ModelState.IsValid)
{
//Perform Something
return View();
}
return View();
}
上述情况不绑定表单上输入的值。它为 NameModel 设置了 null。
我不想使用 EditorFor,因为我必须向助手提供 html 和自定义属性。部分视图的绑定失败。它在注册视图中给我对象引用错误。如上所述,我如何使用具有这种 Model 类层次结构的强类型 Partial 视图?
【问题讨论】:
-
2 种方式。 1)创建一个包含两个模型的
superclass。 2)使用部分带有子动作的方法。子操作将实例化视图模型并将其传递给您的局部视图。 -
感谢@DaveA。你能解释一下这些选项吗?我没完全明白。
-
您可以创建一个包含 NameModel 和 RegisterModel 的类并将其传递给您的视图。然后,您可以在使用 RegisterModel 绑定控件时将 @Model.NameModel 传递给您的部分。
-
或者,您可以为您的部分创建一个子操作。带有子动作的 Partial 使用语法 Html.Action("Action Name") 调用...子动作可以实例化模型并将其传递给局部...
标签: c# asp.net-mvc razor partial-views strongly-typed-view