我有NameModel和RegisterModel以及SuperClass类,如下所示: -
案例1: - 使用SuperClass
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),然后我使用Controller Action方法如下
我的注册视图是注册模型的强类型,如下所示: -
@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和自定义属性。部分视图的绑定失败。在注册视图中给出了对象引用错误。如何使用如上所述的此类模型类层次结构的强类型部分视图?
答案 0 :(得分:2)
最简单的方法是使用子动作
@model MyNamespace.Models.Register.SuperModel
@{
Layout = "~/Views/_Layout.cshtml";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
@Html.Action("MyNamePartialView")
</div>
@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" />
}
让你的行动接受2个课程
public ActionResult Register(RegisterModel RegisterInfo, NameModel NameInfo)