使用ASP.NET MVC的验证使用jQuery AJAX? [英] Use ASP.NET MVC validation with jquery ajax?

查看:214
本文介绍了使用ASP.NET MVC的验证使用jQuery AJAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的ASP.NET MVC的行动是这样的:

 公众的ActionResult编辑(EditPostViewModel数据)
{

}
 

EditPostViewModel 有验证属性是这样的:

  [显示(NAME =...,说明=...)]
[StringLength(100,MinimumLength = 3,的ErrorMessage =...)]
[需要()]
公共字符串名称{获取;组; }
 

在视图中,我使用下面的助手:

  @ Html.LabelFor(型号=> Model.EditPostViewModel.Title,真)

 @ Html.TextBoxFor(型号=> Model.EditPostViewModel.Title,
                        新{@class =TB1,@Style =宽度:400像素; })
 

如果我做一个提交表单,这个文本框放置在验证将首先在客户端,然后服务( ModelState.IsValid )完成的。

现在我有几个问题:

  1. 可以这样使用jQuery AJAX使用提交呢?什么我做的是简单地删除表格和点击提交按钮,一个JavaScript将收集数据,然后运行 $。阿贾克斯

  2. 将在服务器端 ModelState.IsValid 工作?

  3. 好像使用IM的构建INT验证我如何能转发的验证问题返回到客户端和present它(@ Html.ValidationSummary <$ C C $>(真))

Ajax调用的例子:

 函数SendPost(actionPath){
    $阿贾克斯({
        网址:actionPath,
        键入:POST,
        数据类型:JSON,
        数据:
        {
            文本:$('#EditPostViewModel_Text)VAL()。
            标题:$('#EditPostViewModel_Title)VAL()。
        },
        成功:功能(数据){
            警报(成功);
        },
        错误:函数(){
            警报('错误');
        }
    });
}
 

编辑1:

包括页:

 &LT;脚本的src =/脚本/ jQuery的-1.7.1.min.js&GT;&LT; / SCRIPT&GT;
&LT;脚本的src =/脚本/ jquery.validate.min.js&GT;&LT; / SCRIPT&GT;
&LT;脚本的src =/脚本/ jquery.validate.unobtrusive.min.js&GT;&LT; / SCRIPT&GT;
 

解决方案

客户端

使用 jQuery.validate 库应该是pretty的简单设置。

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

 &LT;的appSettings&GT;
    &LT;添加键=ClientValidationEnabled值=真/&GT;
    &LT;添加键=UnobtrusiveJavaScriptEnabled值=真/&GT;
&LT; /的appSettings&GT;
 

当你建立你的观点,你会这样定义的东西:

  @ Html.LabelFor(型号=&GT; Model.EditPostViewModel.Title,真)
@ Html.TextBoxFor(型号=&GT; Model.EditPostViewModel.Title,
                                新{@class =TB1,@Style =宽度:400像素; })
@ Html.ValidationMessageFor(型号=&GT; Model.EditPostViewModel.Title)
 

注:这些都需要一个表单元素中定义

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

 &LT;脚本SRC =@ Url.Content(〜/脚本/ jquery.validate.js)类型=文/ JavaScript的'&GT;&LT; / SCRIPT&GT;
&LT;脚本SRC =@ Url.Content(〜/脚本/ jquery.validate.unobtrusive.js)类型=文/ JavaScript的'&GT;&LT; / SCRIPT&GT;
 

这应该能够设置你的客户端验证

资源

  • <一个href="http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvccustomvalidation_topic5.aspx">http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvccustomvalidation_topic5.aspx

服务器端

注意:这是只对 jQuery.validation

之上额外的服务器端验证

也许这样的事情可以帮助:

  [ValidateAjax]
公共JsonResult编辑(EditPostViewModel数据)
{
    //保存数据
    返回JSON(新{成功= TRUE});
}
 

其中, ValidateAjax 是定义为一个属性:

 公共类ValidateAjaxAttribute:ActionFilterAttribute
{
    公众覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
    {
        如果(!filterContext.HttpContext.Request.IsAjaxRequest())
            返回;

        VAR的ModelState = filterContext.Controller.ViewData.ModelState;
        如果(!modelState.IsValid)
        {
            VAR errorModel =
                    从x在modelState.Keys
                    那里的ModelState [X] .Errors.Count&GT; 0
                    选择新
                           {
                               键= X,
                               错误的ModelState = [X] .Errors。
                                                      选择(Y =&GT; y.ErrorMessage)。
                                                      的ToArray()
                           };
            filterContext.Result =新JsonResult()
                                       {
                                           数据= errorModel
                                       };
            filterContext.HttpContext.Response.Status code =
                                                  (INT)的HTTPStatus code.BadRequest;
        }
    }
}
 

这样做是返回指定所有模型错误的JSON对象。

例的反应是

  [{
    钥匙:姓名,
    错误:[名称字段是必需的。]
},
{
    钥匙:说明,
    错误:说明字段是必需的。]
}]
 

这将返回到您的错误处理 $。阿贾克斯调用回调

您可以通过返回的数据设置为需要的基础上,返回键(我认为像 $('输入[名称=+ err.key +']的错误消息循环')会发现你的输入元素

I have simple ASP.NET MVC action like this :

public ActionResult Edit(EditPostViewModel data)
{

}

The EditPostViewModel have validation attributes like this :

[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
[Required()]
public string Title { get; set; }

In the view I am using the following helpers :

 @Html.LabelFor(Model => Model.EditPostViewModel.Title, true)

 @Html.TextBoxFor(Model => Model.EditPostViewModel.Title, 
                        new { @class = "tb1", @Style = "width:400px;" })

If I do a submit on a form that this textbox is placed in a validation will be done first on client and then on service(ModelState.IsValid).

Now I got a couple of questions :

  1. Can this be used with jQuery ajax submit instead? What I am doing is simply remove the form and on clicking the submit button a javascript will gather data and then run the $.ajax.

  2. Will the server side ModelState.IsValid work?

  3. How can I forward validation problem back to the client and present it as if Im using the build int validation(@Html.ValidationSummary(true))?

Example of Ajax call :

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

Edit 1:

Included on page :

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

解决方案

Client Side

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

Specify the following settings in your Web.config file:

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

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:

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

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

这篇关于使用ASP.NET MVC的验证使用jQuery AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆