将 ASP.NET MVC 验证与 jquery ajax 一起使用? [英] Use ASP.NET MVC validation with jquery ajax?
问题描述
我有这样的简单 ASP.NET MVC 操作:
I have simple ASP.NET MVC action like this :
public ActionResult Edit(EditPostViewModel data)
{
}
EditPostViewModel
具有如下验证属性:
[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
[Required()]
public string Title { get; set; }
在视图中,我使用了以下助手:
In the view I am using the following helpers :
@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title,
new { @class = "tb1", @Style = "width:400px;" })
如果我在表单上提交此文本框放置在验证中的表单,则将首先在客户端上完成,然后在服务上完成(ModelState.IsValid
).
If I do a submit on a form that this textbox is placed in a validation will be done first on client and then on service(ModelState.IsValid
).
现在我有几个问题:
这可以与 jQuery ajax submit 一起使用吗?我正在做的只是删除表单并单击提交按钮,javascript 将收集数据,然后运行
$.ajax
.
服务器端 ModelState.IsValid
会工作吗?
Will the server side ModelState.IsValid
work?
如何将验证问题转发回客户端并将其呈现为我使用构建 int 验证(@Html.ValidationSummary(true)
)?
How can I forward validation problem back to the client and present it as if Im using the build int validation(@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>
推荐答案
客户端
使用 jQuery.validate
库应该很容易设置.
在您的 Web.config
文件中指定以下设置:
Specify the following settings in your Web.config
file:
<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)
注意:这些需要在表单元素中定义
NOTE: These need to be defined within a form element
那么您需要包含以下库:
Then you would need to include the following libraries:
<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
注意:这仅用于在 jQuery.validation
库之上进行额外的服务器端验证
NOTE: This is only for additional server side validation on top of jQuery.validation
library
也许这样的事情会有所帮助:
Perhaps something like this could help:
[ValidateAjax]
public JsonResult Edit(EditPostViewModel data)
{
//Save data
return Json(new { Success = true } );
}
其中 ValidateAjax
是定义为的属性:
Where ValidateAjax
is an attribute defined as:
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 对象,指定您的所有模型错误.
What this does is return a JSON object specifying all of your model errors.
示例响应是
[{
"key":"Name",
"errors":["The Name field is required."]
},
{
"key":"Description",
"errors":["The Description field is required."]
}]
这将返回到 $.ajax
调用的错误处理回调
This would be returned to your error handling callback of the $.ajax
call
您可以根据返回的键循环遍历返回的数据以根据需要设置错误消息(我认为类似于 $('input[name="' + err.key + '"]')
会找到你的输入元素
You can loop through the returned data to set the error messages as needed based on the Keys returned (I think something like $('input[name="' + err.key + '"]')
would find your input element
这篇关于将 ASP.NET MVC 验证与 jquery ajax 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!