mvc ajax提交validate,Use ASP.NET MVC validation with jquery ajax?

Client Side

Using the jQuery.validate library should be pretty simple to set up.

Specify the following settings in your Web.config file:

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:

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

Resources

Server Side

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

}

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;

}

}

}

What this does is return a JSON object specifying all of your model errors.

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值