0

何时可以更改另一个元素上的类!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);
}

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

4

1 回答 1

2

您试图实现的目标会在您的控制器和视图之间引入耦合,这从根本上违背了 MVC(关注点分离)背后的理念。您的控制器不应该对您的视图一无所知,因此我强烈建议您在视图中使用 jQuery/javascript 执行此操作。只需返回一个包含无效属性名称的 viewbag 并使用 jquery 添加错误类。

于 2012-09-08T06:17:28.783 回答