当ModelState无效时操作其他元素

时间:2012-09-07 22:54:01

标签: asp.net-mvc-3 validation modelstate

是否可以在!ModelState.IsValid

时更改其他元素的类

我的观点(简化如下)将<div class="control">包围每个<input>字段

@using(Html.BeginForm("AddRole","Admin", FormMethod.Post, new { @class = "ajax" })) {
    <div class="control">
        @Html.TextBoxFor(x => x.Role, new { @class = "input-xlarge", @placeholder = Html.DisplayNameFor(x => x.Role)})
        @Html.ValidationMessageFor(x => x.Role)
    </div>
}

$(function () {
    $('form.ajax').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    location.reload(true);
                } else {
                    $(this).html(result);
                }
            }
        });
        return false;
    });
});

和我的控制员......

[HttpPost]
public ActionResult AddRole(RoleModel model) {
    if(!ModelState.IsValid) {
        return PartialView("_AddRolePartial", model);
    }
    try {
        System.Web.Security.Roles.CreateRole(model.Role);
        return Json(new {success = true});
    } catch(Exception) {
        ModelState.AddModelError("", "Role creation unsuccessful.");
    }

    return PartialView("_AddRolePartial", model);
}

我希望能够为模型中任何无效的属性添加类errordiv.control。我想我可以通过jQuery在ajax成功事件中处理这个问题,但也许有更好的解决方案。

1 个答案:

答案 0 :(得分:2)

你想要实现的目标会引入你的控制器和你的观点之间的耦合,这从根本上反对MVC背后的想法(关注点分离)。您的控制器不应该知道您的视图,所以我强烈建议您在视图中使用jQuery / javascript。只需返回包含无效属性名称的viewbag,并使用jquery添加错误类。

相关问题