asp.net - 尽管 asp.net mvc 4 验证失败,jquery post 仍然会通过

标签 asp.net asp.net-mvc jquery asp.net-mvc-4

我想要一个 asp.net mvc 表单发布到 Controller ,并显示错误或成功消息,所有这些都使用 jquery。我希望仅当表单验证成功时才会发生此 jquery 帖子。在发布到服务器之前,验证应该在客户端进行。问题是,即使表单验证失败,帖子也会发生。看起来整个表格都在发回,但我不能确定这一点。我正在使用mvc框架中的数据注释来验证。这是代码

查看

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

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

型号

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

最佳答案

发生这种情况是因为当您按下提交的输入类型时,表单无论如何都会提交,只需尝试将 return false 添加到您的 jquery 函数

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

将此行代码添加到 Controller

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

关于asp.net - 尽管 asp.net mvc 4 验证失败,jquery post 仍然会通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18436284/

相关文章:

javascript - 如何在同一 View 的3个不同 View 模型下使用3个不同的数据表?

c++ - 使用 C++ AI 引擎和 ASP.NET C# 页面的纸牌游戏

c# - 可为空数据类型的 jQuery 验证

ASP.NET AJAX 应用程序在 VPN 上速度极慢

javascript - Bootstrap 模式无法关闭

javascript - e.stopPropagation 不适用于 mouseenter 事件

jquery - 如何使用 jquery 更改页面加载时的元素名称?

javascript - jquery 提高每个函数选择器的性能

c# - aspx控件的呈现id在源html代码中总是呈现相同的吗?

c# - ASP.NET 5 EF7 代码优先迁移默认按字母顺序创建列