1. 概述
本章内容包括: 实现客户端验证、使用Javascript和DOM控制程序行为、使用原型继承(prototypal inheritance)扩展对象、使用Ajax实现页面局部刷新、使用JQuery实现UI操作。
2. 主要内容
2.1 实现客户端验证
① 模型: 在MVC程序中,模型 负责管理应用程序的数据和行为。模型也可以用来验证进入程序的数据。
data annotation是可以放置到每一个属性上的规则,用来实现数据验证。
using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations; namespace ArticleApp.Models { public class Article { public int ID { get; set; } [Required] [StringLength(50,MinimumLength=5)] public string Title { get; set; } [RegularExpression[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}")]
AuthorEmail { get; set;} [DataType(DataType.Date)] [Range(300, 3000)] public int NumberOfAuthors { get; set; } [Required] public DateTime CreateDate { get; set; } [Required] public string Description { get; set; } [Range(1, 250)] [DataType(DataType.Currency)] [Required] public decimal Price { get; set; } } public class ArticleDBContext : DbContext { public DbSet<Article> Articles { get; set; } } }
② 视图:在MVC程序中,视图用来管理信息的显示。
模型层定义的数据验证规则会传递到视图层,然后可以使用客户端的Javascript来验证。
@model MvcApplication1.Models.Article @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset>
<legend>Articles</legend>
<div class="editor-label"> @Html.LabelFor(model => model.Title) </div>
<div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div>
<div class="editor-label"> @Html.LabelFor(model => model.CreateDate) </div>
<div class="editor-field"> @Html.EditorFor(model => model.CreateDate) @Html.ValidationMessageFor(model => model.CreateDate) </div>
<div class="editor-label"> @Html.LabelFor(model => model.Description) </div>
<div class="editor-field"> @Html.EditorFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) </div>
<div class="editor-label"> @Html.LabelFor(model => model.Price) </div>
<div class="editor-field"> @Html.EditorFor(model => model.Price) @Html.ValidationMessageFor(model => model.Price) </div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
③ 控制器:控制器基类的ModelState属性,包含一些model特性的方法,比较常用的是IsValid属性。
[HttpPost] public ActionResult Create(Article article) { if (ModelState.IsValid) { db.Articles.Add(article); db.SaveChanges(); return RedirectToAction("Index"); } return View(article); }
④ 远程验证
由服务端的action来执行验证操作。
public JsonResult IsUserAvailable(string username) { if (!WebSecurity.UserExists(username)) { return Json(true, JsonRequestBehavior.AllowGet); //AllowGet表示如果用户接受这个返回值,则验证不会重复执行。 } string suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available.", username); for (int i = 1; i < 100; i++) { string altCandidate = username + i.ToString(); if (!WebSecurity.UserExists(altCandidate)) { suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available. Try {1}.", username, altCandidate); break; } } return Json(suggestedUID, JsonRequestBehavior.AllowGet); }
为了确保UI能调用到验证action,需要在模型层添加System.Web.Mvc.Remote 属性。
[Required] [StringLength(6, MinimumLength = 3)] [Remote("IsUserAvailable", "Validation")] [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")] [Editable(true)] public string UserName { get; set; }
还需要修改配置文件以允许服务端远程验证
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
2.2 使用Javascript和DOM控制程序行为
通过访问DOM,Javascript可以展现出强大的控制UI的能力。
<script type="text/javascript">
function changeText(){ document.getElementById('controlled').innerHTML = 'This is modified text'; } </script>
<p id="controlled">This is sample text.</p>
<input type='button' onclick='changeText()' value='Change Text'/>
2.3 使用原型继承(prototypal inheritance)扩展对象
Javascript是一种基于原型的解释型脚本语言。与面向对象语言的最明显区别是,Javascript没有类,只有对象。
可以基于现有对象创建一系列的原型对象,从而实现对象的扩展功能。
var Contact = function(pageTitle) { this.pageTitle = pageTitle; this.bindEvents(); // binding events as soon as the object is instantiated
this.additionalEvents(); // additional events such as DOM manipulation etc
}; var Contact.prototype.bindEvents = function() { $('ul.menu').on('click', 'li.email, $.proxy(this.toggleEmail, this)); }; var Contact.prototype.toggleEmail = function(e) { //Toggle the email feature on the page };
<script src="/path_to_script_from_above/contact.js"></script>
<script>
new Contact("Contact Us"); </script>
2.4 使用Ajax实现页面局部刷新
System.Web.MVC.Ajax命名空间中提供了一些方法来简化Ajax开发。
@model MvcApplication1.Models.Article @{ ViewBag.Title = "Create"; } <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"
/>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script> $(function() { $(".ReleaseDate").datepicker(); }); </script>
<h2>Create</h2> @using (Ajax.BeginForm("PerformAction", new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" })) { <fieldset>
<legend>Article</legend>
<div class="editor-label"> @Html.LabelFor(model => model.Title) </div>
<div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset> } <p id="errorMessage"/>
<script type="text/javascript">
function OnSuccess(response) { //do something
} function OnFailure(response) { //show failure
document.getElementById('errorMessage').innerHTML = 'THERE WAS AN ERROR'; } </script>
<div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
2.5 使用JQuery实现UI操作
JQuery在 操作DOM、动画、事件处理等方面都提供了易用的功能。还包括浏览器兼容性方面。
3. 总结
① 客户端验证是Javascript和ASP.NET MVC支持的重要特性。用于在客户端检测是否有非法的数据进入程序。
② 第三方Javascript库,包括JQuery,在MVC程序的UI设计中很有用。通过访问DOM,Javascript可以完全控制UI的各个方面,且不需要服务端的交互。
③ JQuery不单单是提供了一些UI控件,在动画、事件处理方面也有很好的支持。并且兼容大部分的主流浏览器。
④ Javascript中,可以通过prototype来扩展现有对象的功能。
⑤ 合理使用Ajax,可以开发出动态的、快速响应的、流畅的程序。