我想知道在一个表单中使用多个强类型的局部视图并将其发布回包含视图的局部视图是否是正确的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属性在partials中为空。但是,如果我将各个模型添加到方法签名中,它们就会被填充。我意识到这是因为当字段呈现时,ID会发生更改,所以在Register View中它们看起来像_LoginId,因此无法映射回AccountSetup模型。
accountSetup.UserLogin或accountSetup.SecurityQuestions没有返回值。
[HttpPost]
public ActionResult Register(AccountSetup accountSetup)
{
获取用户登录和安全问题的值。
[HttpPost]
public ActionResult Register(AccountSetup accountSetup, UserLogin userLogin, SecurityQuestions securityQuestions)
{
问题是如何将它们映射回包含视图(AccountSetup)模型的属性,而不必将部分模型添加到方法签名中以获取值?在主视图中使用强类型部分视图是否是一种不好的方法?
@Html.TextBoxFor(mod => mod.LoginId, new { Id = "UserLogin_LoginId" })
如果按照建议去做,我最终会使这个部分特定于主视图的强类型模型属性。如果我有另一个视图想要使用相同的部分,但是UserLogin属性仅仅被命名为LoginCredentials呢?那么我回到了最初的问题,最好还是把标记放回到我的主视图中,因为它并没有解决我的原始问题。 - Coderrob