日期:2014-05-16  浏览次数:21184 次

Asp.Net MVC4系列--进阶篇之AJAX

本章将开始介绍MVC中Ajax的使用

 

以一个非Ajax版本开始

 

Controller

public class PeopleController : Controller
    {
       private readonly Person[] _personData = {
new Person {FirstName = "Iori",LastName = "Lan", Role = Role.Admin},
new Person {FirstName = "Edwin", LastName= "Sanderson", Role = Role.Admin},
new Person {FirstName = "John",LastName = "Griffyth", Role = Role.User},
new Person {FirstName = "Tik",LastName = "Smith", Role = Role.User},
new Person {FirstName = "Anne",LastName = "Jones", Role = Role.Guest}
};
       public ActionResult Index()
       {
           return View("List");
       }
       public ActionResult GetPeople()
       {
           return View("List",_personData);
       }
       [HttpPost]
       public ActionResult GetPeople(string selectedRole)
       {
           if (selectedRole == null || selectedRole == "All")
           {
                returnView("List",_personData);
           }
           var selected = (Role)Enum.Parse(typeof(Role), selectedRole);
           return View("List",_personData.Where(p => p.Role ==selected));
       }
}


 

Model


 public class Person
    {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public Role Role { get; set; }
    }
   public enum Role
    {
       Admin,
       User,
       Guest
    }


 

View

@{
   Layout = null;
}
 
@using MVCAjax.Models
@model IEnumerable<Person>
@{
ViewBag.Title = "GetPeople";
}
<h2>Get People</h2>
<table>
<thead><tr><th>First</th><th>Last</th><th>Role</th></tr></thead>
<tbody>
@foreach (var p in Model) {
<tr>
<td>@p.FirstName</td>
<td>@p.LastName</td>
<td>@p.Role</td>
</tr>
}
</tbody>
</table>
@using (Html.BeginForm()) {
<div>
@Html.DropDownList("selectedRole",new SelectList(
new []{"All"}.Concat(Enum.GetNames(typeof(Role)))))
<button type="submit">Submit</button>
</div>
}


测试:


验证请求类型

在IE中打开F12->Network ,我们可以看到请求的发起者是click操作,因为不是xmlHttpRequest,因而不是ajax请求


 

使用Ajax重构代码

配置Unobstrusiveajax

打开web.config

确保这一行在appconfig节点中:

<add key="UnobtrusiveJavaScriptEnabled"  value="true" />


打开App_Start/BundleConfig.cs,确保已添加(默认已添加):

 

bundles.Add(newScriptBundle("~/bundles/jquery").Include(
                       "~/Scripts/jquery-{version}.js"));
 
           bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(