我有以下顺序的路由规则:
routes.MapPageRoute("Corporate", "Shop/{Category}", "~/Shop.aspx");
routes.MapPageRoute("GiftType", "Shop/{Category}", "~/Shop.aspx");
routes.MapPageRoute("Occasion", "Shop/{Category}", "~/Shop.aspx");
routes.MapPageRoute("Discounted", "Shop/{Category}", "~/Shop.aspx");
routes.MapPageRoute("Featured", "Shop/{Featured}", "~/Shop.aspx");
我正在使用的链接:
<a href="~/Shop/Corporate" title="Corporate Gifts" runat="server">Corporate</a>
<a href="~/Shop/GiftType" title="Shop by Gift Type" runat="server">Gift Type</a>
<a href="~/Shop/Occasion" title="Shop by Occasion" runat="server">Occasion</a>
<a href="~/Shop/Discounted" title="Discounted" runat="server">Discounted</a>
<a href='<%# "~/Shop/"+Eval("Featured") %>' title='<%# Eval("ProductName") %>'
runat="server">
在目标页面的代码隐藏中,以下代码有效,我不知道为什么。 switch 语句正在为“Featured”的“True”值执行?就像我没有根据占位符来区分这些路线?
if (Page.RouteData.Values["Category"] != null)
{
string category = Page.RouteData.Values["Category"].ToString();
switch (category)
{
case ("Corporate"):
Response.Write("Corporate");
break;
case ("GiftType"):
Response.Write("GiftType");
break;
case ("Occasion"):
Response.Write("Occasion");
break;
case ("Discounted"):
Response.Write("Discounted");
break;
// Do not want the following to be picked up here for Category param
case ("True"):
Response.Write("Featured");
break;
}
}
我想在代码方面工作是这样的:
if (Page.RouteData.Values["Category"] != null)
{
string category = Page.RouteData.Values["Category"].ToString();
switch (category)
{
case ("Corporate"):
Response.Write("Corporate");
break;
case ("GiftType"):
Response.Write("GiftType");
break;
case ("Occasion"):
Response.Write("Occasion");
break;
case ("Discounted"):
Response.Write("Discounted");
break;
}
}
else if (Page.RouteData.Values["Featured"].ToString() == "True")
{
Response.Write("Featured");
}
最佳答案
您的类别只需要一条路线:
routes.MapPageRoute("shop-categories", "Shop/{Category}", "~/Shop.aspx");
然后你可以像以前一样构建 URL,或者像
<a id="a1" href="<%$ RouteUrl:Category=Discounted,routename=shop-categories%>" title="Discounted" runat="server">Discounted</a>
我认为你会想要一条不同的路线(为了清楚起见)作为特色,比如
routes.MapPageRoute("featured", "Shop/Featured/{Featured}", "~/Shop.aspx");
和链接(双向):
<a id="A2" href="<%$ RouteUrl:Featured=False,routename=featured%>" title="Featured" runat="server">Featured False</a>
<a id="A3" href="~/Shop/Featured/True" title="Featured" runat="server">Featured True</a>
然后你的代码隐藏:
if (Page.RouteData.Values["Category"] != null)
{
//something
}
else if (Page.RouteData.Values["Featured"] != null)
{
//something
}
像我展示的那样构建链接的好处是,如果您决定更改路线……您不会破坏任何东西。假设您最终不喜欢 URL
/Shop/Featured/
的外观,只是希望它是 /Featured/
,因此您更改了路线:routes.MapPageRoute("featured", "Featured/{Featured}", "~/Shop.aspx");
现在在我上面的示例中,与
id="A2"
的链接仍然有效,而 id="A3"
现在已损坏。关于ASP.NET Web 窗体路由二义性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19071320/