与 jquery ajax 一起使用 ASP.NET MVC 验证?

我有这样一个简单的 ASP.NET MVC 动作:

public ActionResult Edit(EditPostViewModel data)
{


}

The EditPostViewModel have validation attributes like this :

[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
[Required()]
public string Title { get; set; }

在视图中,我使用了以下辅助工具:

 @Html.LabelFor(Model => Model.EditPostViewModel.Title, true)


@Html.TextBoxFor(Model => Model.EditPostViewModel.Title,
new { @class = "tb1", @Style = "width:400px;" })

如果我做一个表格,这个文本框放在一个验证将首先在客户端,然后在服务(ModelState.IsValid)完成提交。

Now I got a couple of questions :

  1. Can this be used with jQuery ajax submit instead? What I am doing is simply remove the form and on clicking the submit button a javascript will gather data and then run the $.ajax.

  2. 服务器端 ModelState.IsValid能正常工作吗?

  3. 如何将验证问题转发给客户机,并将其显示为使用 build int 验证(@Html.ValidationSummary(true)) ?

Ajax 调用示例:

function SendPost(actionPath) {
$.ajax({
url: actionPath,
type: 'POST',
dataType: 'json',
data:
{
Text: $('#EditPostViewModel_Text').val(),
Title: $('#EditPostViewModel_Title').val()
},
success: function (data) {
alert('success');
},
error: function () {
alert('error');
}
});
}

编辑1:

页面内容:

<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
158647 次浏览

你可以这样做:

(考虑到您正在等待 jsondataType: 'json'的响应)

.NET

public JsonResult Edit(EditPostViewModel data)
{
if(ModelState.IsValid)
{
// Save
return Json(new { Ok = true } );
}


return Json(new { Ok = false } );
}

约翰逊:

success: function (data) {
if (data.Ok) {
alert('success');
}
else {
alert('problem');
}
},

如果需要,我还可以解释如何通过返回错误500来实现,并在事件错误(ajax)中获取错误。但对你来说,这可能是个选择

您应该做的是序列化表单数据并将其发送到控制器操作。NET MVC 将使用 MVC 模型绑定特性将表单数据绑定到 EditPostViewModel对象(您的操作方法参数)。

您可以在客户端验证表单,如果一切正常,则将数据发送到服务器。valid()方法将派上用场。

$(function () {


$("#yourSubmitButtonID").click(function (e) {


e.preventDefault();
var _this = $(this);
var _form = _this.closest("form");


var isvalid = _form .valid();  // Tells whether the form is valid


if (isvalid)
{
$.post(_form.attr("action"), _form.serialize(), function (data) {
//check the result and do whatever you want
})
}


});


});

客户端

使用 jQuery.validate库的设置应该非常简单。

Web.config文件中指定以下设置:

<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

When you build up your view, you would define things like this:

@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title,
new { @class = "tb1", @Style = "width:400px;" })
@Html.ValidationMessageFor(Model => Model.EditPostViewModel.Title)

注意: 这些需要在 form 元素中定义

然后,您需要包括以下库:

<script src='@Url.Content("~/Scripts/jquery.validate.js")' type='text/javascript'></script>
<script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")' type='text/javascript'></script>

This should be able to set you up for client side validation

Resources

服务器端

注意: 这仅用于 jQuery.validation库之上的附加服务器端验证

也许这样的东西可以帮助:

[ValidateAjax]
public JsonResult Edit(EditPostViewModel data)
{
//Save data
return Json(new { Success = true } );
}

其中 ValidateAjax是定义为:

public class ValidateAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;


var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode =
(int) HttpStatusCode.BadRequest;
}
}
}

这样做的目的是返回一个指定所有模型错误的 JSON 对象。

Example response would be

[{
"key":"Name",
"errors":["The Name field is required."]
},
{
"key":"Description",
"errors":["The Description field is required."]
}]

This would be returned to your error handling callback of the $.ajax call

您可以循环访问返回的数据,根据返回的键设置所需的错误消息(我认为类似于 $('input[name="' + err.key + '"]')的东西可以找到您的输入元素

这里有一个相当简单的解决方案:

在控制器中,我们像这样返回错误:

if (!ModelState.IsValid)
{
return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
}

Here's some of the client script:

function displayValidationErrors(errors)
{
var $ul = $('div.validation-summary-valid.text-danger > ul');


$ul.empty();
$.each(errors, function (idx, errorMessage) {
$ul.append('<li>' + errorMessage + '</li>');
});
}

That's how we handle it via ajax:

$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
var isSuccessful = (data['success']);


if (isSuccessful) {
$('#partial-container-steps').html(data['view']);
initializePage();
}
else {
var errors = data['errors'];


displayValidationErrors(errors);
}
}
});

此外,我通过 ajax 呈现部分视图的方式如下:

var view = this.RenderRazorViewToString(partialUrl, viewModel);
return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);

RenderRazorViewToString 方法:

public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}

Added some more logic to solution provided by @Andrew Burgess. Here is the full solution:

Created a action filter to get errors for ajax request:

public class ValidateAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;


var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode =
(int)HttpStatusCode.BadRequest;
}
}
}

在我的控制器方法中添加了如下过滤器:

[HttpPost]
// this line is important
[ValidateAjax]
public ActionResult AddUpdateData(MyModel model)
{
return Json(new { status = (result == 1 ? true : false), message = message }, JsonRequestBehavior.AllowGet);
}

添加了一个用于 jquery 验证的通用脚本:

function onAjaxFormError(data) {
var form = this;
var errorResponse = data.responseJSON;
$.each(errorResponse, function (index, value) {
// Element highlight
var element = $(form).find('#' + value.key);
element = element[0];
highLightError(element, 'input-validation-error');


// Error message
var validationMessageElement = $('span[data-valmsg-for="' + value.key + '"]');
validationMessageElement.removeClass('field-validation-valid');
validationMessageElement.addClass('field-validation-error');
validationMessageElement.text(value.errors[0]);
});
}


$.validator.setDefaults({
ignore: [],
highlight: highLightError,
unhighlight: unhighlightError
});


var highLightError = function(element, errorClass) {
element = $(element);
element.addClass(errorClass);
}


var unhighLightError = function(element, errorClass) {
element = $(element);
element.removeClass(errorClass);
}

最后将错误 javascript 方法添加到 Ajax Begin 表单:

@model My.Model.MyModel
@using (Ajax.BeginForm("AddUpdateData", "Home", new AjaxOptions { HttpMethod = "POST", OnFailure="onAjaxFormError" }))
{
}