Bài số 4
Định tuyến URL và điều phối hiển thị
Table of Contents
1 URL routing (Định tuyến URL) .............................................................................................. 2
1.1 Giới thiệu định tuyến URL ....................................................................................................... 2
1.1.1 Hệ thống định tuyến trong ASP.NET MVC làm gì?........................................................ 2
1.1.2 Các quy tắc định tuyến URL mặc định trong ASP.NET MVC Web Application ............. 2
1.2 Ví dụ định tuyến URL............................................................................................................... 3
2 Điều phối hiển thị dữ liệu .......................................................................................................... 6
2.1 Điều phối hiển thị dữ liệu với ViewData Dictionary ................................................................... 6
2.2 Điều phối hiển thị dữ liệu với cách dùng Strongly Typed Classes .............................................. 9
2.2.1 Li ích cua việc dùng strongly typed ............................................................................. 9
2.2.2 Tao strongly-typed DuLieuDanhSachSanPham trong folder Models ............................ 9
2.2.3 Dng ViewData diconary với một đối tưng ViewData strongly typed ................... 11
3 Câu hỏi ôn tập .......................................................................................................................... 11
4 Ti liệu tham khảo .................................................................................................................... 11
Microsoft Vietnam – DPE Team | Bài số 4: Định tuyến URL và điều phối hiển thị
2
1 URL routing (Định tuyến URL)
1.1 Giới thiệu định tuyến URL
1.1.1 H thnh tuyn trong ASP.NET MVC làm gì?
ASP.NET MVC Framework có mt h thnh tuyn URL ( URL Routing System ) linh hot cho phép xác
nh các quy tc ánh x a ch URL bên trong ng dng. Mt h thnh tuyn có 2 m
Xây dng mt tp hp các URL ng dng nh tuyn chúng ti các Controller và thc thi các
x lý.
Xây dng các URL g có th gc tr li Controllers/Actions ( ví d: form posts, liên kt <a
i gi AJAX )
S dng các quy tc ánh x URL u khi m do cho vic lp trình ng
dng, nu mui cu trúc URL ( ví d /Catalog thành /Products ) có th i mt tp hp
quy tc ánh x mc ng dng mà không cn phi vit li mã lp trình bên trong Controllers và Views.
1.1.2 Các quy tnh tuyn URL mnh trong ASP.NET MVC Web Application
Mnh khi to ng dng vi ASP.NET MVC Web Application trong Visual Studio s to ra mt ASP.NET
Application class gi là Global.asax cha cu hình các quy tnh tuyn URL. Xây dnh tuyn thông
c RegisterRoutes(ReouteCollection routes) và khi ng dng b u, c
Application_Start() trong Global.asax.cs s g to ra bnh tuyn.
Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace BanHang
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route
name
"{controller}/{action}/{id}", // URL with
parameters
new { controller = "Home", action = "Index", id = "" } //
Parameter defaults
);
}
Microsoft Vietnam – DPE Team | Bài số 4: Định tuyến URL và điều phối hiển thị
3
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
Mnh tuyn URL trong ASP.NET MVC Framework có cu trúc dng: Controllers/ControllerAction/Id
Vi ASP.NET MVC Web Application thì mnh Controllers là HomeController, mnh ControllerAction là
Index, m nh Id là r i tran c xây dng thông qua template ASP.NET Web
Application thì mnh http://localhost/ vi http://localhost/Home/Index/
Khi ng dng ASP.NET MVC Web Application nhc mt Url, MVC Framework s nh giá các quy tc
nh tuyn trong tp h quynh Controller nào s u khin request.
MVC framework chn Controller bnh giá các quy tc trong bnh tuyn theo trt t sn.
1.2 Ví dụ định tuyến URL
.NET MVC Web Application:
To TimKiem URL
Figure 1. To controller TimKiemController.cs
Microsoft Vietnam – DPE Team | Bài số 4: Định tuyến URL và điều phối hiển thị
4
Có 2 action trong TimKiem hin th mt trang search vi mi
dùng nhp t khóa c u khin khi yêu cu tìm kinh.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace BanHang.Controllers
{
public class TimKiemController : Controller
{
public ActionResult Index()
{
// Add action logic here
return View();
}
public ActionResult Results(string query)
{
return View();
}
}
}
Trong Global.asax.cs mt cách thnh tuyn mnh. Theo quy tnh tuyn mnh thì khi yêu cu mt
trang tìm kia ch c gi theo s ng vi [controller]/[action]/[id] là /TimKiem/Results/[string
query]. Cách dùng này không có v gu mt cách tùy binh tuy i thành
/TimKiem/[string query]. Thêm vào trong Global.asax.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace BanHang
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"TimKiem", // Route
name
"TimKiem/{query}", // URL with parameters
new { controller = "TimKiem", action = "Results" } // Parameter
defaults
);
routes.MapRoute(
"Default", // Route
name
"{controller}/{action}/{id}", // URL with
parameters
Microsoft Vietnam – DPE Team | Bài số 4: Định tuyến URL và điều phối hiển thị
5
new { controller = "Home", action = "Index", id = "" } //
Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
To 2 view hin th d liu khin trong TimKiemController.cs là Index.aspx và Results.aspx
Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
AutoEventWireup="true" CodeBehind="Index.aspx.cs"
Inherits="BanHang.Views.TimKiem.Index" %>
<asp:Content ID="viewTimKiem" ContentPlaceHolderID="MainContent" runat="server">
<form method="post" action="TimKiem/Search">
<input type="text" id="txtTimKiem" name="txtTimKiem" />
<input type="submit" value="Tìm Kiếm" />
</form>
</asp:Content>
Result.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
AutoEventWireup="true" CodeBehind="Results.aspx.cs"
Inherits="BanHang.Views.TimKiem.Results" %>
<asp:Content ID="viewResults" ContentPlaceHolderID="MainContent" runat="server">
Kết quả dữ liệu tìm kiếm được ở đây
</asp:Content>
Thêm vào Views\Shared\Site.master mt tab tìm kim
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs"
Inherits="BanHang.Views.Shared.Site" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"
<html xmlns="
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title><%= Html.Encode(ViewData["Title"]) %></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>My Sample MVC Application</h1>
</div>
<div id="logindisplay">
<% Html.RenderPartial("LoginUserControl"); %>
</div>
<div id="menucontainer">
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>