尽管asp.net mvc 4validation失败,jquerypost仍然经历过

我想要一个asp.net mvc表单发布到控制器,并显示错误或成功的消息,所有这些都使用jquery。 我希望只有在表单validation成功时才会发生此jquerypost。 在发送到服务器的post之前,validation应该是客户端。 问题是,即使表单validation失败,也会发生post。 它看起来似乎整个表格都在发回,但我无法确定。 我在mvc框架中使用Data annotations进行validation。 这是代码

视图

@model jQueryPosts.Models.ModelVM     
@using ( Html.BeginForm("jQueryPost", "Home",null, FormMethod.Post, new { id="FormPost" })) { @Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name)
@Html.TextBoxFor(x => x.LastName) @Html.ValidationMessageFor(x => x.LastName)
@Html.TextBoxFor(x => x.Age) @Html.ValidationMessageFor(x => x.Age)
}
$(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); } }); }); });

控制器

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

将此行代码添加到控制器

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