我很好奇在表单中使用多个强类型部分并回发到包含视图的部分的方法是否是正确的 MVC 处理方法。主视图与以下模型绑定,为简洁起见,省略了其他几个属性和数据注释:
public class AccountSetup : ViewModelBase
{
public bool TermsAccepted { get; set; }
public UserLogin UserLogin { get; set; }
public SecurityQuestions SecurityQuestions { get; set; }
}
public class UserLogin
{
public string LoginId { get; set; }
public string Password { get; set; }
}
主 Register.cshtml 视图的标记并不完全在下面,但下面是部分的使用方式:
@model Models.Account.AccountSetup
. . . <pretty markup> . . .
@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
. . . <other fields and pretty markup> . . .
@Html.Partial("_LoginAccount", Model.UserLogin)
@Html.Partial("_SecurityQuestions", Model.SecurityQuestions)
<input id="btnContinue" type="image" />
}
仅供参考,下面是 _LoginAccount 的部分视图,其中删除了多余的标记。
@model Models.Account.UserLogin
<div>
@Html.TextBoxFor(mod => mod.LoginId)
@Html.PasswordFor(mod => mod.Password)
</div>
问题出在注册后的表单上,部分中包含的 AccountSetup 属性为 null。但是,如果我将各个模型添加到方法签名中,它们就会被填充。我意识到这是因为当字段呈现时 ID 会发生变化,因此它们看起来像 Register View 的 _LoginId,因此它不会映射回 AccountSetup 模型。
无法获取 accountSetup.User Login 或 account Setup.Security Questions 的值
[HttpPost]
public ActionResult Register(AccountSetup accountSetup)
{
获取用户登录和安全问题的值
[HttpPost]
public ActionResult Register(AccountSetup accountSetup, UserLogin userLogin, SecurityQuestions securityQuestions)
{
问题是如何将这些映射回包含视图 (AccountSetup) 模型的属性,而不必将部分模型添加到方法签名只是为了取回值?在主视图中使用强类型部分视图是一种不好的方法吗?