jQuery的后仍能通过asp.net的MVC 4验证失败的inspite [英] jquery post still goes through inspite of asp.net mvc 4 validation failure

查看:135
本文介绍了jQuery的后仍能通过asp.net的MVC 4验证失败的inspite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个asp.net mvc的形式张贴到一个控制器,也显示在错误或成功的消息,所有这一切都使用jQuery。我想只有当表单验证成功,这个jQuery后发生。验证应该是客户端后在服务器发生之前。问题是,在后发生即使当表单验证失败。它也像整个窗体回发,但我不能肯定这一点。我使用的数据注解的MVC框架来验证。这里是code

查看

  @model jQueryPosts.Models.ModelVM
<链接HREF =@ Url.Content(〜/内容/的site.css)的rel =stylesheet属性类型=文/ CSS/>
<脚本的src =@ Url.Content(〜/脚本/ jQuery的-1.8.3.min.js)TYPE =文/ JavaScript的>< / SCRIPT>
<脚本的src =@ Url.Content(〜/脚本/ jquery.validate.min.js)TYPE =文/ JavaScript的>< / SCRIPT>
<脚本的src =@ Url.Content(〜/脚本/ jquery.validate.unobtrusive.min.js)TYPE =文/ JavaScript的>< / SCRIPT>< D​​IV>
    @using(Html.BeginForm(jQueryPost,家,空,FormMethod.Post,新{ID =FormPost}))
    {
   @ Html.TextBoxFor(X => x.Name)@ Html.ValidationMessageFor(X => x.Name)
        < BR />
    @ Html.TextBoxFor(X => x.LastName)@ Html.ValidationMessageFor(X => x.LastName)
        < BR />
    @ Html.TextBoxFor(X => x.Age)@ Html.ValidationMessageFor(X => x.Age)
        < BR />    <输入类型=提交值=提交/>
    }
< / DIV><脚本>    $(文件)。就绪(函数(){        $('#FormPost')。提交(函数(五){
            亦即preventDefault(); //此行将prevent从提交表单
            警报('ajax的帖子在这里');            $阿贾克斯({
                输入:POST,
                网址:$('#FormPost')ATTR(行动)。
                数据:$('#FormPost')序列化()。
                接受:应用/ JSON,
                错误:功能(XHR,状态,错误){                    警报('错误:'+ xhr.responseText +' - '+误差);                },
                成功:函数(响应){
                    警报('RESP:'+响应);
                }
            });
        });
    }); < / SCRIPT>

控制器

 的[AcceptVerbs(HttpVerbs.Post)
    公共JsonResult jQueryPost(ModelVM VM)
    {
        ModelVM _vm = VM;        尝试
        {
            //一些code在这里
        }
        抓住
        {
            Response.Status code = 406; //或其他任何适当的地位code。
            的Response.Write(自定义错误消息);
            返回null;
        }        返回JSON(名贴的是:+ _vm.Name);
    }

MODEL

 使用System.ComponentModel.DataAnnotations;命名空间JQ.Example
{
    公共类ModelVM
    {
        [必需(的ErrorMessage =请输入名字)]
        公共字符串名称{;组; }
           [需要]
        公共字符串名字{获得;组; }
           [需要]
        公众诠释年龄{搞定;组; }
    }
}


解决方案

它发生,因为当你$提交表单的对$ PSS输入类型总会被提出,只是尝试添加返回false到你的jQuery函数

  $('#FormPost')。提交(函数(五){
        变种验证= $(#FormPost)有效();
        如果(验证)
        {
         $阿贾克斯({
            输入:POST,
            网址:$('#FormPost')ATTR(行动)。
            数据:$('#FormPost')序列化()。
            接受:应用/ JSON,
            错误:功能(XHR,状态,错误){                警报('错误:'+ xhr.responseText +' - '+误差);            },
            成功:函数(响应){
                警报('RESP:'+响应);
            }
         });
        }        返回false;
    });

添加此行code到控制器

 如果(ModelState.IsValid)
{
  ...
}
其他
{
   ModelState.AddModelError(钥匙,messege);
}

I want an asp.net mvc form to post to a controller and also show a message on error or success, all of which using jquery. I want this jquery post to happen only if the form validation is successful. The validation should be client side before the post to the server happens. The problem is that the post happens even when the form validation has failed. It also looks like the entire form is posting back, but I cant be sure of that. I am using Data annotations in the mvc framework to validate. Here is the code

View

@model jQueryPosts.Models.ModelVM
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.8.3.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<div>
    @using ( Html.BeginForm("jQueryPost", "Home",null, FormMethod.Post, new { id="FormPost" }))
    { 
   @Html.TextBoxFor(x => x.Name)  @Html.ValidationMessageFor(x => x.Name) 
        <br />
    @Html.TextBoxFor(x => x.LastName) @Html.ValidationMessageFor(x => x.LastName) 
        <br />
    @Html.TextBoxFor(x => x.Age)  @Html.ValidationMessageFor(x => x.Age) 
        <br />

    <input type=submit value="submit" />
    }
</div>

<script>

    $(document).ready(function () {

        $('#FormPost').submit(function (e) {
            e.preventDefault(); //This line will prevent the form from submitting
            alert('ajax post here');

            $.ajax({
                type: 'POST',
                url: $('#FormPost').attr('action'),
                data: $('#FormPost').serialize(),
                accept: 'application/json',
                error: function (xhr, status, error) {

                    alert('error: ' + xhr.responseText + '-' + error);

                },
                success: function (response) {
                    alert('resp: ' + response);
                }
            });
        });


    });

 </script>

The Controller

   [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult jQueryPost(ModelVM vm)
    {
        ModelVM _vm = vm;

        try
        {
            //some code here
        }
        catch
        {
            Response.StatusCode = 406; // Or any other proper status code.
            Response.Write("Custom error message");
            return null;
        }

        return Json("name posted was: " + _vm.Name);
    }

MODEL

using System.ComponentModel.DataAnnotations;

namespace JQ.Example
{
    public class ModelVM
    {
        [Required(ErrorMessage="Please enter first name") ]
        public string Name { get; set; }
           [Required]
        public string LastName { get; set; }
           [Required]
        public int Age { get; set; }
    }
}

解决方案

it happens since when you press input type of submit the form will be submit anyway, just try to add return false to your jquery function

$('#FormPost').submit(function (e) {            
        var validated = $("#FormPost").valid();
        if(validated)
        {
         $.ajax({
            type: 'POST',
            url: $('#FormPost').attr('action'),
            data: $('#FormPost').serialize(),
            accept: 'application/json',
            error: function (xhr, status, error) {

                alert('error: ' + xhr.responseText + '-' + error);

            },
            success: function (response) {
                alert('resp: ' + response);
            }
         });
        }

        return false;
    });

add this line of code to controller

if (ModelState.IsValid)
{
  ...
}
else
{
   ModelState.AddModelError("key", "messege");
}

这篇关于jQuery的后仍能通过asp.net的MVC 4验证失败的inspite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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