问题
I'm curious about whether the approach of using multiple strongly typed partials within a form that posts back to the partial containing View is the right MVC approach to doing things. The main View is bound with the following model with several other properties and data annotations omitted for brevity:
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; }
}
The markup of the main Register.cshtml View isn't totally below, but this is how the partials are used below:
@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" />
}
Just for reference the partial view of _LoginAccount is below with excess markup removed.
@model Models.Account.UserLogin
<div>
@Html.TextBoxFor(mod => mod.LoginId)
@Html.PasswordFor(mod => mod.Password)
</div>
The problem is on the form post to the Register the AccountSetup properties are null that were contained in the partials. However, if I add the individual models to the method signature they get filled. I realize it's because when the fields render the ID gets changed so they look like _LoginId for the Register View so it doesn't map back to the AccountSetup model.
Doesn't get values back for accountSetup.UserLogin or accountSetup.SecurityQuestions
[HttpPost]
public ActionResult Register(AccountSetup accountSetup)
{
Gets values back for userLogin and securityQuestions
[HttpPost]
public ActionResult Register(AccountSetup accountSetup, UserLogin userLogin, SecurityQuestions securityQuestions)
{
The question is how does one map these back to the containing Views (AccountSetup) model's properties without having to add the partial's models to the method signature just to get the values back? Is this a bad approach using strongly typed partial views within a main view?
回答1:
This is because your Partial views are strongly typed. Remove the @model declaration in your Partials and access the Model properties like this
@Html.Partial("_LoginAccount")
and then in your partial
<div>
@Html.TextBoxFor(mod => mod.UserLogin.LoginId)
@Html.PasswordFor(mod => mod.UserLogin.Password)
</div>
回答2:
All partials views should be strongly typed with the same view model (AccountSetup in your case) :
@model Models.Account.AccountSetup
@Html.TextBoxFor(mod => mod.UserLogin.LoginId)
@Html.PasswordFor(mod => mod.UserLogin.Password)
Then:
@Html.Partial("_LoginAccount", Model)
来源:https://stackoverflow.com/questions/8592136/mvc-3-razor-form-post-w-multiple-strongly-typed-partial-views-not-binding