Một ví dụ đơn giản về cách sử dụng định tuyến trong ASP.NET
- Tạo Rỗng Web Application
- Thêm hình thức đầu tiên - Default.aspx
- Add biểu mẫu thứ hai - Second.aspx
- Thêm biểu mẫu thứ ba - Third.aspx
Thêm vào mặc định.aspx 3 nút -
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Second.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Third.aspx?Name=Pants");
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("Third.aspx?Name=Shoes");
}
đọc chuỗi truy vấn vào thứ ba trang
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.QueryString["Name"]);
}
Bây giờ nếu bạn chạy chương trình, bạn sẽ có thể điều hướng đến hình thức thứ hai và thứ ba. Đây là cách nó được sử dụng để được. Hãy thêm định tuyến.
Thêm mục mới - Global.aspx using System.Web.Routing;
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"HomeRoute",
"Home",
"~/Default.aspx"
);
routes.MapPageRoute(
"SecondRoute",
"Second",
"~/Second.aspx"
);
routes.MapPageRoute(
"ThirdRoute",
"Third/{Name}",
"~/Third.aspx"
);
}
Trong default.aspx sửa đổi protected void Button1_Click (object sender, EventArgs e) { // Response.Redirect ("Second.aspx"); Response.Redirect (GetRouteUrl ("SecondRoute", null)); }
protected void Button2_Click(object sender, EventArgs e)
{
//Response.Redirect("Third.aspx?Name=Pants");
Response.Redirect(GetRouteUrl("ThirdRoute", new {Name = "Pants"}));
}
protected void Button3_Click(object sender, EventArgs e)
{
// Response.Redirect("Third.aspx?Name=Shoes");
Response.Redirect(GetRouteUrl("ThirdRoute", new { Name = "Shoes" }));
}
Sửa tải trang trong third.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write(Request.QueryString["Name"]);
Response.Write(RouteData.Values["Name"]);
}
Chạy chương trình, xin vui lòng lưu ý url trông sạch hơn nhiều - có được không nộp phần mở rộng trong đó (Second.aspx trở thành chỉ Thứ hai)
Để chuyển tiếp thì một đối số
thêm nút mới để default.aspx với đoạn mã sau:
protected void Button4_Click(object sender, EventArgs e)
{
Response.Redirect(GetRouteUrl("FourthRoute", new { Name = "Shoes" , Gender = "Male"}));
}
Thêm mã sau đây để global.asax
routes.MapPageRoute(
"FourthRoute",
"Fourth/{Name}-{Gender}",
"~/Fourth.aspx"
);
tạo trang Fourth.aspx như sau tải trang:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Name is: " + RouteData.Values["Name"] + " and Gender is " + RouteData.Values["Gender"]);
}
vui lòng định tuyến url cho bài đăng của bạn – Armstrongest