微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc-3 – 具有多个强类型部分视图的MVC 3 Razor表格帖子没有绑定

我很好奇在一个回复到包含部分View的表单中使用多个强类型部分的方法是否是正确的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,包含在partials中.但是,如果我将单个模型添加方法签名中,则会填充它们.我意识到这是因为当字段呈现时ID被更改,因此它们看起来像注册视图的_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)模型的属性,而不必将部分模型添加方法签名只是为了获取值?在主视图中使用强类型部分视图这是一种不好的方法吗?

解决方法

这是因为您的部分视图是强类型的.删除Partials中的@model声明,然后像这样访问Model属性
@Html.Partial("_LoginAccount")

然后在你的部分

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐