我想要一个 asp.net mvc 表单发布到控制器并显示错误或成功消息,所有这些都使用 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>
控制器
[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; }
}
}