2

我有一个 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>

_User部分视图

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

动态动作用户模型

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);
}
4

0 回答 0