ASP.NET MVC的奇怪行为

时间:2013-12-06 19:00:42

标签: c# asp.net-mvc-5

我有以下型号:

public class EditUserViewModel : AddEditUserViewModelPartial
{
    public string OldUsername { get; set; }
    public int UserId { get; set; }
    public bool? NewPasswordGenerated { get; set; }
}

public class AddEditUserViewModelPartial
{
    [Required]
    [Display(Name = "Username/Email")]
    public string UserName { get; set; }

    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
....

public class AddEditUserPartial
{
    public TypeOfForm Type { get; set; }
    public AddEditUserViewModelPartial Model { get; set; }
}

public enum TypeOfForm
{
    ADD,
    EDIT
}

部分名称:

    @model CHFN.Models.AddEditUserPartial

    <div class="form-group">
        @Html.LabelFor(m => m.Model.UserName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Model.UserName, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Model.UserName)
        </div>
    </div>
    ....

编辑用户:

@model CHFN.Models.EditUserViewModel

    @Html.AntiForgeryToken()
    <h4>Edit the account.</h4>
    <hr />
    @Html.HiddenFor(p => p.OldUsername)
    @Html.HiddenFor(p => p.UserId)
    @Html.HiddenFor(p => p.NewPasswordGenerated)
    @Html.ValidationSummary(true)
    @Html.Partial("PartialAddEditUser",
            new CHFN.Models.AddEditUserPartial()
        {
            Type = CHFN.Core.TypeOfForm.EDIT,
            Model = new CHFN.Models.AddEditUserViewModelPartial() { UserName = Model.UserName, Fullname = Model.Fullname, Roles = Model.Roles, Password = Model.Password, ConfirmPassword = Model.ConfirmPassword }
        })

到EditUser(post)是一个空的OldUsername,UserId,NewPasswordGenerated。而且,对我来说更惊讶,如果我删除Html.Partial(“PartialAddEditUser”,...) - 那么OldUsername,UserId,NewPasswordGenerated不为空。为什么会这样?

1 个答案:

答案 0 :(得分:1)

问题似乎是您正在为主视图和局部视图使用不同的模型。

在局部视图中考虑以下行:

@Html.LabelFor(m => m.Model.UserName, ...)

当您将数据发回到期望(我假设)EditUserViewModel作为输入模型的操作时,MVC将尝试在Model上找到名为EditUserViewModel的属性(这是不存在。),并在其上设置UserName属性。

解决方案可能是根本不使用AddEditUserPartial类。部分调用可能看起来像这样:

@Html.Partial("PartialAddEditUser", Model);

然后可以将局部视图简化为以下(注意我们使用完全相同的模型,从而摆脱额外的.Model):

@model CHFN.Models.EditUserViewModel

<div class="form-group">
    @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.UserName)
    </div>
</div>
....