栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

客户端

使用该

jQuery.validate
库应该非常简单。

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

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

建立视图时,您将定义如下内容:

@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)

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

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

<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){    //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对象,该对象指定所有模型错误。

示例响应将是

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

这将返回到您的错误处理回调

$.ajax
调用

您可以遍历返回的数据以根据返回的键根据需要设置错误消息(我认为类似的东西

$('input[name="' + err.key +'"]')
会找到您的输入元素



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/399734.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号