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

客户端

使用该jQuery.validate库应该非常简单。

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

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

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

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

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

这应该能够使您进行客户端验证

资源资源

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 + '"]')会找到您的输入元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值