现在补上URL路由的学习,至于蒋老师自建的MVC小引擎和相关案例就放在论文提交后再实践咯。通过ASP.NET的路由系统,可以完成请求URL与物理文件的分离,其优点是:灵活性、可读性、SEO优化。接下来通过一个最简单的路由例子进入这部分的学习,这是一个蒋老师提供的WebForm路由的例子,回想起刚做ASP.NET时,每次看到.aspx页面的前台代码时的茫然和无措,茫茫多的标签,属性,数据源的绑定吓死小兄弟俺了,也花过不少时间去理解记忆,效果不也不大。现在回头看看感觉好了很多,看到IsPostback老亲切了,觉得在理解的基础上拖拉控件也是很幸福的事情,嘿嘿。
1 void Application_Start(object sender, EventArgs e) 2 { 3 //路由配置 4 var defaults = new RouteValueDictionary { { "name", "*" }, { "id", "*" } }; 5 RouteTable.Routes.MapPageRoute("default", "employees/{name}/{id}", "~/Default.aspx", true, defaults); 6 } 7 8 //前台代码 9 <form id="form1" runat="server"> 10 <div> 11 <asp:GridView ID="GridViewEmployees" runat="server" AutoGenerateColumns="False" Width="100%"> 12 <Columns> 13 <asp:HyperLinkField DataNavigateUrlFields="Name,Id" DataNavigateUrlFormatString="~/employees/{0}/{1}" DataTextField="Name" HeaderText="姓名" /> 14 <asp:BoundField DataField="Gender" HeaderText="性别" /> 15 <asp:BoundField DataField="Birthday" DataFormatString="{0:dd/MM/yyyy}" HeaderText="出生日期" /> 16 <asp:BoundField DataField="Department" HeaderText="部门" /> 17 </Columns> 18 </asp:GridView> 19 <asp:DetailsView ID="DetailsViewEmployee" runat="server" Height="50px" Width="100%" AutoGenerateRows="False"> 20 <Fields> 21 <asp:BoundField DataField="Id" HeaderText="ID" /> 22 <asp:BoundField DataField="Name" HeaderText="姓名" /> 23 <asp:BoundField DataField="Gender" HeaderText="性别" /> 24 <asp:BoundField DataField="Birthday" DataFormatString="{0:dd/MM/yyyy}" HeaderText="出生日期" /> 25 <asp:BoundField DataField="Department" HeaderText="部门" /> 26 </Fields> 27 </asp:DetailsView> 28 </div> 29 </form> 30 31 //后台代码 32 public partial class Default : System.Web.UI.Page 33 { 34 private EmployeeRepository _repository; 35 public EmployeeRepository Repository 36 { 37 get 38 { 39 return null == _repository ? _repository = new EmployeeRepository() : _repository; 40 } 41 } 42 43 protected void Page_Load(object sender, EventArgs e) 44 { 45 if (this.IsPostBack) 46 { 47 return; 48 } 49 string employeeId = this.RouteData.Values["id"] as string; 50 if (employeeId == "*" || string.IsNullOrEmpty(employeeId)) 51 { 52 this.GridViewEmployees.DataSource = this.Repository.GetEmployees(); 53 this.GridViewEmployees.DataBind(); 54 this.DetailsViewEmployee.Visible = false; 55 } 56 else 57 { 58 this.DetailsViewEmployee.DataSource = this.Repository.GetEmployees(employeeId); 59 this.DetailsViewEmployee.DataBind(); 60 this.GridViewEmployees.Visible = false; 61 } 62 } 63 }