如何在 ASP.NET 中使用路由的简单示例
- 创建空 Web 应用程序
- 添加第一个表单 - Default.aspx
- 添加第二种形式 - Second.aspx
- 添加第三种形式 - Third.aspx
添加到 default.aspx 3 个按钮 -
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");
}
在第三页读取查询字符串
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.QueryString["Name"]);
}
现在,如果您运行该程序,您将能够导航到第二种和第三种形式。这就是过去的样子。让我们添加路由。
使用 System.Web.Routing 添加新项目 - Global.aspx;
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"
);
}
在 default.aspx 中修改 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" }));
}
在third.aspx中修改页面加载
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write(Request.QueryString["Name"]);
Response.Write(RouteData.Values["Name"]);
}
运行程序,请注意 url 看起来更干净 - 里面没有文件扩展名(Second.aspx 变成了 Second)
传递不止一个参数
使用以下代码向 default.aspx 添加新按钮:
protected void Button4_Click(object sender, EventArgs e)
{
Response.Redirect(GetRouteUrl("FourthRoute", new { Name = "Shoes" , Gender = "Male"}));
}
将以下代码添加到 global.asax
routes.MapPageRoute(
"FourthRoute",
"Fourth/{Name}-{Gender}",
"~/Fourth.aspx"
);
使用以下页面加载创建 Fourth.aspx 页面:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Name is: " + RouteData.Values["Name"] + " and Gender is " + RouteData.Values["Gender"]);
}