Ivy*_*Ivy 116 validation ajax asp.net-mvc jquery
我有这样简单的ASP.NET MVC动作:
public ActionResult Edit(EditPostViewModel data)
{
}
Run Code Online (Sandbox Code Playgroud)
在EditPostViewModel具有验证属性是这样的:
[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
[Required()]
public string Title { get; set; }
Run Code Online (Sandbox Code Playgroud)
在视图中,我使用以下帮助程序:
@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title,
new { @class = "tb1", @Style = "width:400px;" })
Run Code Online (Sandbox Code Playgroud)
如果我在表单上提交此文本框放在验证中,将首先在客户端上完成,然后在service(ModelState.IsValid)上完成.
现在我有几个问题:
这可以与jQuery ajax提交一起使用吗?我正在做的只是删除表单,然后单击提交按钮javascript将收集数据,然后运行$.ajax.
服务器端会ModelState.IsValid工作吗?
如何将验证问题转发回客户端并将其呈现为使用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');
}
});
}
Run Code Online (Sandbox Code Playgroud)
编辑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>
Run Code Online (Sandbox Code Playgroud)
And*_*ess 149
设置jQuery.validate库应该非常简单.
在Web.config文件中指定以下设置:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)
构建视图时,您可以定义以下内容:
@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)
Run Code Online (Sandbox Code Playgroud)
注意:这些需要在表单元素中定义
然后,您需要包含以下库:
<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>
Run Code Online (Sandbox Code Playgroud)
这应该可以为您设置客户端验证
注意:这仅适用于jQuery.validation库顶部的其他服务器端验证
也许这样的事情可能有所帮助:
[ValidateAjax]
public JsonResult Edit(EditPostViewModel data)
{
//Save data
return Json(new { Success = true } );
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样做是返回一个JSON对象,指定所有模型错误.
示例响应将是
[{
"key":"Name",
"errors":["The Name field is required."]
},
{
"key":"Description",
"errors":["The Description field is required."]
}]
Run Code Online (Sandbox Code Playgroud)
这将返回到您的错误处理回调的$.ajax调用
您可以根据返回的键循环返回的数据以根据需要设置错误消息(我觉得类似$('input[name="' + err.key + '"]')会找到您的输入元素
Shy*_*yju 39
您应该做的是序列化表单数据并将其发送到控制器操作.ASP.NET MVC将EditPostViewModel使用MVC模型绑定功能将表单数据绑定到对象(您的操作方法参数).
您可以在客户端验证表单,如果一切正常,请将数据发送到服务器.该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
})
}
});
});
Run Code Online (Sandbox Code Playgroud)
这是一个相当简单的解决方案:
在控制器中,我们返回如下错误:
if (!ModelState.IsValid)
{
return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
这是一些客户端脚本:
function displayValidationErrors(errors)
{
var $ul = $('div.validation-summary-valid.text-danger > ul');
$ul.empty();
$.each(errors, function (idx, errorMessage) {
$ul.append('<li>' + errorMessage + '</li>');
});
}
Run Code Online (Sandbox Code Playgroud)
这就是我们通过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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
另外,我通过ajax以下列方式呈现部分视图:
var view = this.RenderRazorViewToString(partialUrl, viewModel);
return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
为@Andrew Burgess 提供的解决方案添加了更多逻辑。这是完整的解决方案:
创建了一个动作过滤器来获取 ajax 请求的错误:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
将过滤器添加到我的控制器方法中:
[HttpPost]
// this line is important
[ValidateAjax]
public ActionResult AddUpdateData(MyModel model)
{
return Json(new { status = (result == 1 ? true : false), message = message }, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
添加了用于 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);
}
Run Code Online (Sandbox Code Playgroud)
最后在我的 Ajax Begin 表单中添加了错误 javascript 方法:
@model My.Model.MyModel
@using (Ajax.BeginForm("AddUpdateData", "Home", new AjaxOptions { HttpMethod = "POST", OnFailure="onAjaxFormError" }))
{
}
Run Code Online (Sandbox Code Playgroud)