在ASP.NET MVC中将JQuery AJAX与Model验证一起使用
Using JQuery AJAX along with Model Validation in ASP.NET MVC
_Layout.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - ASP.NET MVC Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - ASP.NET MVC Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
BundleConfig.cs
using System.Web;
using System.Web.Optimization;
namespace AjaxDemo
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
BundleTable.EnableOptimizations = true;
}
}
}
ContactViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace AjaxDemo.Models
{
public class ContactViewModel
{
[Required]
public string FirstName
{
get;
set;
}
[Required]
public string LastName
{
get;
set;
}
}
}
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using AjaxDemo.Models;
namespace AjaxDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(ContactViewModel model)
{
if(!ModelState.IsValid)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Not valid model");
}
return Json(model, "json");
}
}
}
Index.cshtml
@model AjaxDemo.Models.ContactViewModel
@{
ViewBag.Title = "AJAX Demo";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post,
new { id = "frmContact", name = "frmContact" }))
{
<div class="form-group">
@Html.LabelFor(model => model.FirstName,
new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName,
new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
}
<div id="loading">
<p>Loading...</p>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
$("#loading").hide();
$('#btnSubmit').click(function () {
if ($("#frmContact").valid()) {
$('#frmContact').submit();
}
else {
return false;
}
});
$("#frmContact").on("submit", function (event) {
event.preventDefault();
$("#loading").show();
$('#btnSubmit').attr('disabled', 'disabled');
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
url: url,
type: "POST",
data: formData,
dataType: "json",
success: function (response) {
alert('Success!');
},
error: function (response)
{
alert('Error!');
},
complete: function () {
$("#loading").hide();
$('#btnSubmit').removeAttr('disabled');
}
})
});
});
</script>
@Scripts.Render("~/bundles/jqueryval")
}