c# - MVC4 中的部分模型验证

标签 c# asp.net-mvc validation asp.net-mvc-4

我有一个 PartialView,它是一种用于创建或修改用户并实现 ViewModel DynamicActionUserModel 的表单。引用此 partialView 的 View 显示所有 MembershipUsers 的表,并提供创建新用户 Membership.CreateUser() 或修改用户 'Membership.UpdateUser() `。 partialView 中的表单向我的 Controller 发送一个 ajax post 以提交数据。

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

也许我的模型和 View 的设计需要更改,或者是否有一种方法可以验证模型但在修改用户时忽略密码?不确定这方面的最佳做法是什么。

我想另一种选择是创建另一个 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; }

}

Controller

[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>

局部 View

@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"/>
}

最佳答案

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

关于c# - MVC4 中的部分模型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12991155/

相关文章:

c# - 如何在 Windows 窗体中实例化大量按钮?

asp.net-mvc - ASP.NET MVC - 根据 Active Directory 对用户进行身份验证,但需要输入用户名和密码

asp.net-mvc - 返回一个 View 模型类型与传递的不同的 mvc 操作

java - 如何访问 UIComponent 属性中链接的 bean?

ruby-on-rails - Rails simple_form text_area 不显示错误

c# - 如何在 C# 中绑定(bind)到 Grid ColumnDefinition Width

c# - 系统 IO 异常 : the process cannot access the file because it is being used by another process c#

c# - 加快在 C# 中处理大字符串数组的速度

asp.net-mvc - ASP.NET MVC 将数据从 View 传递到 Controller

javascript - 如何为 AngularJS 表单编写通用错误处理程序