猿问

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

我有这样简单的ASP.NET MVC操作:


public ActionResult Edit(EditPostViewModel data)

{


}

该EditPostViewModel有这样的验证特性:


[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;" })

如果我在将该文本框置于验证中的表单上进行提交,则将首先在客户端上执行,然后在service(ModelState.IsValid)上完成。


现在我有几个问题:


可以将其与jQuery ajax提交一起使用吗?我正在做的就是简单地删除表单,然后单击“提交”按钮,javascript将收集数据,然后运行$.ajax。


服务器端可以ModelState.IsValid工作吗?


如何将验证问题转发回客户端,并像使用生成intvalidation(@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>


哆啦的时光机
浏览 941回答 3
3回答

缥缈止盈

客户端使用该jQuery.validate库应该非常简单。在Web.config文件中指定以下设置:<appSettings>&nbsp; &nbsp; <add key="ClientValidationEnabled" value="true"/>&nbsp;&nbsp; &nbsp; <add key="UnobtrusiveJavaScriptEnabled" value="true"/>&nbsp;</appSettings>建立视图时,您将定义以下内容:@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)@Html.TextBoxFor(Model => Model.EditPostViewModel.Title,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new { @class = "tb1", @Style = "width:400px;" })@Html.ValidationMessageFor(Model => Model.EditPostViewModel.Title)注意:这些需要在表单元素中定义然后,您需要包括以下库:<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>这应该能够使您进行客户端验证资源资源http://msdn.microsoft.com/zh-cn/vs2010trainingcourse_aspnetmvccustomvalidation_topic5.aspx服务器端注意:这仅用于jQuery.validation库顶部的其他服务器端验证也许这样的事情可能会有所帮助:[ValidateAjax]public JsonResult Edit(EditPostViewModel data){&nbsp; &nbsp; //Save data&nbsp; &nbsp; return Json(new { Success = true } );}当ValidateAjax一个属性定义为:public class ValidateAjaxAttribute : ActionFilterAttribute{&nbsp; &nbsp; public override void OnActionExecuting(ActionExecutingContext filterContext)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!filterContext.HttpContext.Request.IsAjaxRequest())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; var modelState = filterContext.Controller.ViewData.ModelState;&nbsp; &nbsp; &nbsp; &nbsp; if (!modelState.IsValid)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var errorModel =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; from x in modelState.Keys&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; where modelState[x].Errors.Count > 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select new&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;key = x,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;errors = modelState[x].Errors.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Select(y => y.ErrorMessage).&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ToArray()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filterContext.Result = new JsonResult()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Data = errorModel&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filterContext.HttpContext.Response.StatusCode =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (int) HttpStatusCode.BadRequest;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}这样做是返回一个JSON对象,该对象指定所有模型错误。示例响应将是[{&nbsp; &nbsp; "key":"Name",&nbsp; &nbsp; "errors":["The Name field is required."]},{&nbsp; &nbsp; "key":"Description",&nbsp; &nbsp; "errors":["The Description field is required."]}]这将返回到您的错误处理回调$.ajax调用您可以遍历返回的数据以根据返回的键根据需要设置错误消息(我认为类似的东西$('input[name="' + err.key + '"]')会找到您的输入元素

芜湖不芜

这是一个相当简单的解决方案:在控制器中,我们返回如下错误:if (!ModelState.IsValid)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Json(new { success = false, errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList() }, JsonRequestBehavior.AllowGet);&nbsp; &nbsp; &nbsp; &nbsp; }以下是一些客户端脚本:function displayValidationErrors(errors){&nbsp; &nbsp; var $ul = $('div.validation-summary-valid.text-danger > ul');&nbsp; &nbsp; $ul.empty();&nbsp; &nbsp; $.each(errors, function (idx, errorMessage) {&nbsp; &nbsp; &nbsp; &nbsp; $ul.append('<li>' + errorMessage + '</li>');&nbsp; &nbsp; });}这就是我们通过ajax处理它的方式:$.ajax({&nbsp; &nbsp; cache: false,&nbsp; &nbsp; async: true,&nbsp; &nbsp; type: "POST",&nbsp; &nbsp; url: form.attr('action'),&nbsp; &nbsp; data: form.serialize(),&nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; var isSuccessful = (data['success']);&nbsp; &nbsp; &nbsp; &nbsp; if (isSuccessful) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#partial-container-steps').html(data['view']);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; initializePage();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var errors = data['errors'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; displayValidationErrors(errors);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }});另外,我通过以下方式通过ajax渲染部分视图:var view = this.RenderRazorViewToString(partialUrl, viewModel);&nbsp; &nbsp; &nbsp; &nbsp; return Json(new { success = true, view }, JsonRequestBehavior.AllowGet);RenderRazorViewToString方法:public string RenderRazorViewToString(string viewName, object model)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; ViewData.Model = model;&nbsp; &nbsp; &nbsp; &nbsp; using (var sw = new StringWriter())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;viewName);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var viewContext = new ViewContext(ControllerContext, viewResult.View,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ViewData, TempData, sw);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; viewResult.View.Render(viewContext, sw);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return sw.GetStringBuilder().ToString();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

JQuery
我要回答