前面的文章我们介绍了jquery.validate.unobtrusive 脚本实现Asp.net MVC3表单验证。这里我们介绍应用jquery.unobtrusive-ajax.js实现的ajax操作.首先确保的是在Web.config中配置节:
<add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
我们有一个_register.cshtml的PartialView :
<script type="text/javascript"> function ReloadForm(xhr) { $('#formcontent').html(xhr.responseText); } function ClearValidationErrors() { $('.validation-summary-errors').html(''); $('.input-validation-error').removeClass('input-validation-error'); $('.field-validation-error').remove(); } </script> @using (Ajax.BeginForm("IndexPost", "Home", Model, new AjaxOptions { UpdateTargetId = "formresults", HttpMethod = "Post", OnSuccess = "ClearValidationErrors", OnFailure = "ReloadForm(xhr)" })) { @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.") <div> <fieldset> <legend>Account Information</legend> <div class="editor-label"> @Html.LabelFor(m => m.UserName) </div> <div class="editor-field"> @Html.TextBoxFor(m => m.UserName) @Html.ValidationMessageFor(m => m.UserName) </div> <div class="editor-label"> @Html.LabelFor(m => m.Email) </div> <div class="editor-field"> @Html.TextBoxFor(m => m.Email) @Html.ValidationMessageFor(m => m.Email) </div> <div class="editor-label"> @Html.LabelFor(m => m.Password) </div> <div class="editor-field"> @Html.PasswordFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password) </div> <div class="editor-label"> @Html.LabelFor(m => m.ConfirmPassword) </div> <div class="editor-field"> @Html.PasswordFor(m => m.ConfirmPassword) @Html.ValidationMessageFor(m => m.ConfirmPassword) </div> <p> <input type="submit" value="Register" /> </p> </fieldset> </div> }
上面的代码,我们使用了AjaxOptions,这样帮我们指定要更新UpdateTargetId,调用成功要执行的Js function,以及失败以后执行Js function. 这里当我们的ajax调用成功后我们返回一个叫”_result.cshtml”的partialView,内容是这样的:
<h2>Thanks for registering!</h2> <p>You have successfully registered</p>
在_Layout.cshtml中定义一个header节:
@if(IsSectionDefined("Header"))
{
@RenderSection("Header")
}
下面是主要用示演的Index.cshtml的内容. 你可以看到一个id叫formresults,AJAX调用成功后将会更新它:
@model AjaxTest.Models.RegisterModel @{ ViewBag.Title = "Home Page"; } @section Header { <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> <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> } <h2>@ViewBag.Message</h2> <div id="formcontent"> @{ Html.RenderPartial("_register", Model); } </div> <div id="formresults"></div>
Controller的代码是这样的,IndexPost Action就是我们Ajax的Post 目标.
public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(new AjaxTest.Models.RegisterModel()); } [HttpPost] public ActionResult IndexPost(AjaxTest.Models.RegisterModel model) { if (ModelState.IsValid) { return PartialView("_results"); } HttpContext.Response.StatusCode = 500; HttpContext.Response.Clear(); return PartialView("_register", model); }
Model是这样的:
public class RegisterModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } }
当View执行时我们看到这样的HTML,你可以看到Form 标签加上了 data-ajax,data-ajax-method等特性, 而input上data-* 用来做验证:
<form action="/Home/IndexPost" data-ajax="true" data-ajax-failure="ReloadForm(xhr)" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="ClearValidationErrors" data-ajax-update="#formresults" id="form0" method="post"> <div> <fieldset> <legend>Account Information</legend> <div class="editor-label"> <label for="UserName">User name</label> </div> <div class="editor-field"> <input data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span> </div> <div class="editor-label"> <label for="Email">Email address</label> </div> <div class="editor-field"> <input data-val="true" data-val-required="The Email address field is required." id="Email" name="Email" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span> </div> <div class="editor-label"> <label for="Password">Password</label> </div> <div class="editor-field"> <input data-val="true" data-val-length="The Password must be at least 6 characters long." data-val-length-max="100" data-val-length-min="6" data-val-required="The Password field is required." id="Password" name="Password" type="password" /> <span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true"></span> </div> <div class="editor-label"> <label for="ConfirmPassword">Confirm password</label> </div> <div class="editor-field"> <input data-val="true" data-val-equalto="The password and confirmation password do not match." data-val-equalto-other="*.Password" id="ConfirmPassword" name="ConfirmPassword" type="password" /> <span class="field-validation-valid" data-valmsg-for="ConfirmPassword" data-valmsg-replace="true"></span> </div> <p> <input type="submit" value="Register" /> </p> </fieldset> </div> </form>
你有兴趣可以查看Asp.net MVC 3 RTM的源代码,下面是来AjaxOptions类ToUnobtrusiveHtmlAttributes方法,你可以看到data-*与表单中生成的一致。
public IDictionary<string, object> ToUnobtrusiveHtmlAttributes() { var result = new Dictionary<string, object> { { "data-ajax", "true" }, }; AddToDictionaryIfSpecified(result, "data-ajax-url", Url); AddToDictionaryIfSpecified(result, "data-ajax-method", HttpMethod); AddToDictionaryIfSpecified(result, "data-ajax-confirm", Confirm); AddToDictionaryIfSpecified(result, "data-ajax-begin", OnBegin); AddToDictionaryIfSpecified(result, "data-ajax-complete", OnComplete); AddToDictionaryIfSpecified(result, "data-ajax-failure", OnFailure); AddToDictionaryIfSpecified(result, "data-ajax-success", OnSuccess); if (!String.IsNullOrWhiteSpace(LoadingElementId)) { result.Add("data-ajax-loading", "#" + LoadingElementId); if (LoadingElementDuration > 0) { result.Add("data-ajax-loading-duration", LoadingElementDuration); } } if (!String.IsNullOrWhiteSpace(UpdateTargetId)) { result.Add("data-ajax-update", "#" + UpdateTargetId); result.Add("data-ajax-mode", InsertionModeUnobtrusive); } return result; }
希望对您开发有帮助,您可能感兴趣的文章:
HTML5中custom data-*特性与asp.net mvc 3 表单验证
Html 5中自定义data-*特性
作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。