【发布时间】:2012-09-07 22:54:00
【问题描述】:
!ModelState.IsValid时是否可以更改另一个元素上的类?
我的视图,简化如下,每个 <input> 字段周围都有 <div class="control">
@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 处理这个问题,但也许有一个更好的解决方案。
【问题讨论】:
标签: asp.net-mvc-3 validation modelstate