加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 04:06:02 所属栏目:asp.Net 来源:网络整理
导读:我很好奇在一个回复到包含部分View的表单中使用多个强类型部分的方法是否是正确的MVC处理方法.为简洁起见,主视图与以下模型绑定,其中包含其他几个属性和数据注释: public class AccountSetup : ViewModelBase{ public bool TermsAccepted { get; set; } pub
我很好奇在一个回复到包含部分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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读