2011-12-21 33 views
7

我很好奇在表单中使用多个强类型部分的方法是否回到部分包含View是正确的MVC方法来处理。主视图绑定与略去了一些其他的属性和数据注解以下模型:MVC 3 Razor Form Post带有多个强类型部分视图无法绑定

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被更改时,它们看起来像RegisterLog View的_LoginId,因此它不会映射回AccountSetup模型。

没有得到值回accountSetup.UserLogin或accountSetup.SecurityQuestions

[HttpPost] 
    public ActionResult Register(AccountSetup accountSetup) 
    { 

获取值回USERLOGIN和securityQuestions

[HttpPost] 
    public ActionResult Register(AccountSetup accountSetup, UserLogin userLogin, SecurityQuestions securityQuestions) 
    { 

现在的问题是如何一回这些映射到包含Views(AccountSetup)模型的属性,而不必为了获取值而将局部模型添加到方法签名?这是在主视图中使用强类型局部视图的不好方法吗?

回答

0

这是因为您的部分视图是强类型的。在局部模板移除@model声明,像这样访问

@Html.Partial("_LoginAccount") 

模型属性,然后在局部

<div> 
    @Html.TextBoxFor(mod => mod.UserLogin.LoginId) 
    @Html.PasswordFor(mod => mod.UserLogin.Password) 
</div> 
+0

如果有的话我会觉得做类似下面会比建议的更改一个更好的方法: @ Html.TextBoxFor(MOD => mod.LoginId,新{ID =“UserLogin_LoginId”}) 如果我一样建议我最终将该部分特定于主视图的强类型模型属性。如果我有另一个想要使用相同部分的视图,但是UserLogin属性简单地命名为LoginCredentials?然后,我回过头来看,我的主要观点只是把标记放回原处,因为它不能解决我原来的问题。 – Coderrob 2011-12-23 03:11:39

+0

您是否找到解决此问题的方法? – Buzzer 2012-05-15 20:48:50

0

所有的谐音意见应与同一视图模型是强类型(AccountSetup在情况下):

@model Models.Account.AccountSetup 

@Html.TextBoxFor(mod => mod.UserLogin.LoginId) 
@Html.PasswordFor(mod => mod.UserLogin.Password) 

然后:

@Html.Partial("_LoginAccount", Model) 
相关问题