我有NameModel和RegisterModel和超类的类如下: -使用强类型的另一个强类型的视图中的局部视图
案例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并没有超 使用@ 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设置为空。
我不想使用EditorFor,因为我必须为helpers提供html和自定义属性。局部视图的绑定fails.it在注册视图中给我提供了对象引用错误。我如何使用如上所述的这样的Model类层次结构来使用这种强类型的部分视图?
2种方式。 1)创建一个包含两种模型的“超类”。 2)使用部分儿童行为方法。子动作将实例化并将视图模型传递给你的部分。 – 2013-04-29 16:33:01
谢谢@DaveA。你能解释一下选项吗?我没有完全明白。 – user2232861 2013-04-29 16:50:16
您可以创建一个包含NameModel和RegisterModel的类,并将其传递给您的视图。然后,您可以将@ Model.NameModel传递给您的部分,同时使用RegisterModel绑定您的控件。 – 2013-04-29 18:11:18