學習ASP.NET MVC5架構揭秘筆記-ASP.NET路由(二),mvc5-asp.net
執行個體示範:通過路由實現請求地址與.aspx頁面的映射
我們建立一個簡單的ASP.NET Web Forms應用,並採用一套獨立於.aspx檔案路徑的URL來訪問對應的Web頁面,兩者之間的映射通過路由來實現,我們依然沿用員工管理的情境。
首先我們將員工的所有資訊(ID、姓名、性別、出生日期和所在部門)定義在如下所示的Employee類型中,然後定義一個EmployeeRepository類型來維護員工列表的資料。簡單起見,員工列表通過靜態欄位employees表示。EmployeeRepository的GetEmployees方法根據指定的ID返回對應的員工。如果指定的ID為“*”,則返回所有員工列表。
public class Employee { public string Id { get; private set; } public string Name { get; private set; } public string Gender { get; private set; } public DateTime BirthDate { get; private set; } public string Department { get; private set; } public Employee(string id, string name, string gender,DateTime birthDate, string department) { this.Id = id; this.Name = name; this.Gender = gender; this.BirthDate = birthDate; this.Department = department; } } public class EmployeeRepository { private static IList<Employee> employees; static EmployeeRepository() { employees = new List<Employee>(); employees.Add(new Employee(Guid.NewGuid().ToString(), "張三", "男", new DateTime(1981, 8, 24), "銷售部")); employees.Add(new Employee(Guid.NewGuid().ToString(), "李四", "女", new DateTime(1982, 7, 10), "人事部")); employees.Add(new Employee(Guid.NewGuid().ToString(), "王五", "男", new DateTime(1981, 9, 21), "人事部")); } public IEnumerable<Employee> GetEmployees(string id = "") { return employees.Where(e => e.Id == id || string.IsNullOrEmpty(id) || id == "*"); } }
要通過一個獨立於實體路徑的URL來訪問該.aspx頁面,就要利用路由來實現兩者之間的映射。我們將實現映射的路由註冊代碼定義在Global.asax檔案中。如下面的程式碼片段所示,我們在Application_Start方法中通過RouteTable的Routes屬性得到表示全域路由表的RouteCollection對象,並調用其MapPageRoute方法將頁面的路徑與一個路由模板進行映射。
public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { var defaults = new RouteValueDictionary { { "name", "*" }, { "id", "*" } }; RouteTable.Routes.MapPageRoute("", "employees/{name}/{id}","~/default.aspx", true, defaults); } }
作為MapPageRoute方法最後一個參數的RouteValueDictionary對象用於提供定義在路由模板中兩個路由變數(“{name}”和“{id}”)的預設值。如果我們為定義路由模板中的路由變數指定了預設值,在當前請求地址的後續部分缺失的情況下,路由系統會採用提供的預設值對該地址進行填充之後再進行模式比對。在如上的程式碼片段中,我們將{name}和{id}兩個變數的預設值均指定為“*”。對於針對URL為“/employees”的請求,註冊的Route會將其格式化成“/employees/*/*”,後者無疑與定義的路由模板的模式相匹配。
我們在Default.aspx頁面中分別採用GridView和DetailsView來顯示所有員工列表和某個列表的詳細詳細。GridView模板中顯示為員工姓名的HyperLinkField的串連採用了什麼定義在模板(employees/{name}/{id})中的模式。
<form id="form1" runat="server"> <div id="page"> <asp:GridView ID="GridViewEmployees" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-bordered"> <Columns> <asp:HyperLinkField HeaderText="姓名" DataTextField="Name" DataNavigateUrlFields="Name,Id" DataNavigateUrlFormatString="~/employees/{0}/{1}" /> <asp:BoundField DataField="Gender" HeaderText="性別" /> <asp:BoundField DataField="BirthDate" HeaderText="出生日期" DataFormatString="{0:dd/MM/yyyy}" /> <asp:BoundField DataField="Department" HeaderText="部門" /> </Columns> </asp:GridView> <asp:DetailsView ID="DetailsViewEmployee" runat="server" AutoGenerateRows="false" Width="100%" CssClass="table table-bordered"> <Fields> <asp:BoundField DataField="ID" HeaderText= "ID" /> <asp:BoundField DataField="Name" HeaderText= "姓名" /> <asp:BoundField DataField="Gender" HeaderText="性別" /> <asp:BoundField DataField="BirthDate" HeaderText="出生日期" DataFormatString="{0:dd/MM/yyyy}" /> <asp:BoundField DataField="Department" HeaderText="部門" /> </Fields> </asp:DetailsView> </div> </form>
由於所有員工列表和單一員工的詳細資料均體現在這個頁面中,所以我們需要根據具體的請求地址來判斷應該呈現怎樣的資料,這是通過代表當前頁面的page對象的RouteData屬性來實現的。Page類型的RouteData屬性返回一個RouteData對象,他表示路由系統對當前請求進行解析得到的路由資料。RouteData的Value屬性是一個儲存路由變數的字典,其Key為變數名稱。在如下所示的程式碼片段中,我們得到表示員工ID的路由變數(RouteData.Values[“id”]),如果它是預設值(*)就表示當前請求是針對員工列表的,反之則是針對指定的某個具體員工。
public partial class Default : System.Web.UI.Page { private EmployeeRepository repository; public EmployeeRepository Repository { get { return repository ?? (repository = new EmployeeRepository()); } } protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) { return; } string employeeId = this.RouteData.Values["id"] as string; if (employeeId == "*" || string.IsNullOrEmpty(employeeId)) { this.GridViewEmployees.DataSource = this.Repository.GetEmployees(); this.GridViewEmployees.DataBind(); this.DetailsViewEmployee.Visible = false; } else { var employees = this.Repository.GetEmployees(employeeId); this.DetailsViewEmployee.DataSource = employees; this.DetailsViewEmployee.DataBind(); this.GridViewEmployees.Visible = false; } } }