MVC4:ModelState.IsValid始终返回true

时间:2012-10-12 19:44:52

标签: asp.net-mvc validation asp.net-mvc-4 model-validation

我有一个PartialView,其中包含一个异步将数据发布到我的控制器的表单。如果ModelState有效,控制器将添加用户,否则,它将返回带有无效模型的PartialView。我遇到的问题是ModelState无论如何总是有效的。我可以看到表单正在被正确序列化,并且正在填充DynamicActionUserModel.RegisterModel的所有属性。

我不明白为什么会出现这种情况,但模型绑定是否可行,因为我在模型中有模型?

这是我的代码......

查看

@model IEnumerable<RobotDog.Models.UserModel>
<!-- other stuff -->
<div class="createUser">
    @Html.Partial("_UserPartial", new DynamicActionUserModel { Action = "CreateUser", RegisterModel = new RegisterModel() })    
</div>
<script type="text/javascript">
$(function () {
    $('form.ajax').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.success) {
                        location.reload(true);
                    } else {
                        $('.createUser').html(result);                          
                    }
                }
            });
        }
        return false;
    });
});
</script>

_UserPartial View

@model RobotDog.Models.DynamicActionUserModel

@using(Html.BeginForm(Model.Action,"Admin", FormMethod.Post, new { @class = "ajax" })) {
    @Html.ValidationSummary(true, "Registration unsuccessful. Please correct errors and try again.")

    @Html.TextBoxFor(x => x.RegisterModel.Email, new { @class = "input-xlarge", @placeholder = "Email"})
    @Html.TextBoxFor(x => x.RegisterModel.UserName, new { @class = "input-xlarge", @placeholder = "User Name"})
    @Html.PasswordFor(x => x.RegisterModel.Password, new { @class = "input-xlarge", @placeholder = "Password"})
    @Html.ListBoxFor(x => x.RegisterModel.SelectedRoles, Model.RegisterModel.Roles)
    <input type="submit" value="Submit" class="btn"/>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

DynamicActionUserModel

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

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

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    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 { return new MultiSelectList(System.Web.Security.Roles.GetAllRoles()); }
    }
}

控制器

[HttpPost]
public ActionResult CreateUser(DynamicActionUserModel model) {
    if (!ModelState.IsValid) {
        foreach(var value in ModelState.Values) {
            foreach (var error in value.Errors) {
                ModelState.AddModelError(string.Empty, error.ErrorMessage);
            }
        }
        return PartialView("_UserPartial", model);
    }

    try { 
        ...
        return Json(new { success = true });
    }
    catch(Exception e) { ... }

    return PartialView("_UserPartial", model);
}

0 个答案:

没有答案