3

我有一个PartialView用于创建或修改用户并实现 ViewModel 的表单DynamicActionUserModel。引用此 partialView 的视图显示了一个表,MembershipUsers并提供了创建新用户Membership.CreateUser()或修改用户“Membership.UpdateUser()”的能力。partialView 中的表单向我的控制器发送 ajax 以提交数据。

我遇到的问题是,当创建用户时,他们的用户名、电子邮件、密码和角色被序列化回控制器DynamicActionUserModel.RegisterModel并进行验证,但是当用户被修改时,密码不是可用的属性(也不是我想让它可以在客户端修改)所以它没有设置DynamicActionUserModel.RegisterModel并且ModelState.IsValid总是错误的。

也许我的模型和视图的设计需要更改,或者有没有办法验证模型但在修改用户时忽略密码?不确定这个的最佳实践是什么。

我想另一种选择是创建另一个 ViewModel 和另一个 partialView 专门用于修改用户,但这似乎很草率。

模型

public class DynamicActionUserModel {
    public string Action { get; set; }
    public RegisterModel RegisterModel { get; set; }
}

public class RegisterModel {
    [Required]
    [Display(Name = "User Name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [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 string[] SelectedRoles { get; set; }
    public MultiSelectList Roles { get; set; }

}

控制器

[HttpGet]
public ActionResult CreateUser() {
    var model = new DynamicActionUserModel {
        Action = "CreateUser",
        RegisterModel = new RegisterModel {
            Roles = new MultiSelectList(System.Web.Security.Roles.GetAllRoles())
        }
    };

    return PartialView("_UserPartial", model);
}

[HttpGet]
public ActionResult ModifyUser() {
    var model = new DynamicActionUserModel {
        Action = "ModifyUser",
        RegisterModel = new RegisterModel {
            Roles = new MultiSelectList(System.Web.Security.Roles.GetAllRoles())
        }
    };

    return PartialView("_UserPartial", model);
}

[HttpPost]
public ActionResult ModifyUser(DynamicActionUserModel model) {
    bool isEqual = true;

    if(!ModelState.IsValid) { // this is always false because password is empty
        return PartialView("_UserPartial", model);
    }

    var user = Membership.GetUser(model.RegisterModel.UserName);
    // do stuff
    Membership.UpdateUser(user);

    return Json(new {success = false});
}

看法

@using RobotDog.Models
@model IEnumerable<RobotDog.Models.UserModel>

<!-- table of users -->
<div class="modify-form">
    @Html.Action("ModifyUser")
</div>
<div class="create-user-form">
    @Html.Action("CreateUser")
</div>

部分视图

@model RobotDog.Models.DynamicActionUserModel

@using(Html.BeginForm(Model.Action,"Admin", FormMethod.Post, new { @class = "ajax" })) {
    <!-- Email -->
    @Html.TextBoxFor(x => x.RegisterModel.Email, new { @class = inputSize, placeholder = "Email"})

    <!-- UserName -->
    @if(Model.Action == "ModifyUser") {
        @Html.HiddenFor(x => x.RegisterModel.UserName)
        <span class="input-xlarge uneditable-input">@Html.DisplayNameFor(x => x.RegisterModel.UserName)</span>
    } else {
        @Html.TextBoxFor(x => x.RegisterModel.UserName, new { @class = inputSize, placeholder = "User Name" })
    }

    <!-- Password -->
    @if(Model.Action == "Createuser") {
        @Html.PasswordFor(x => x.RegisterModel.Password, new { @class = inputSize, placeholder = "Password"})
    }

    <!-- Roles -->
    @Html.ListBoxFor(x => x.RegisterModel.SelectedRoles, Model.RegisterModel.Roles)

    <!-- Submit -->
    <input type="submit" value="Submit" class="btn"/>
}
4

2 回答 2

2

ModelState.Remove("password")在调用之前尝试使用ModelState.IsValid,但如这里建议的那样,如果并非总是需要某个属性,则不应将其标记为必需。

于 2012-10-20T18:09:56.837 回答
0

你看过ModelState.IsValidField吗?

注意:即使从 MVC4 开始,文档也​​是倒退的,应该说:

确定是否有任何与指定键关联或带有前缀的 ModelError 对象。

我为此做了一个小扩展方法助手:

public static class ModelStateHelpers
    {
        public static bool IsValidFor<TModel, TProperty>(this TModel model,
                                                         System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression,
                                                         ModelStateDictionary modelState)
        {
            string name = ExpressionHelper.GetExpressionText(expression);

            return modelState.IsValidField(name);
        }
    }

用法很简单:

 bool billingValid = model.IsValidFor(x => x.CheckoutModel.BillingAddress, ModelState);
于 2012-12-15T05:18:26.793 回答