asp.net mvc 根据路由生成正确的url

假设存在这样一段路由配置:

routes.MapRoute(
name: "ProductList1_01",
url: "pl/{bigSortId}_{smallSortId}_{brandId}.html",
defaults: new { controller = "NewStore", action = "ProductList" },
namespaces: mallNS
);
routes.MapRoute(
name: "ProductList1_02",
url: "pl/{bigSortId}_{smallSortId}.html",
defaults: new { controller = "NewStore", action = "ProductList" },
namespaces: mallNS
);
routes.MapRoute(
name: "ProductList1_03",
url: "pl/{bigSortId}.html",
defaults: new { controller = "NewStore", action = "ProductList" },
namespaces: mallNS
);

 

如果我希望自动匹配到 pl/{bigSortId}_{smallSortId}.html,我会这样写:

@Url.Action("ProductList", new { bigSortId = Model.BigSortId, smallSortId = Model.SmallSortId, brandId = "" })

但如果页面存在form,并且存在向当前页面的post brandId表单元素,可能造成生成这样的Url:

/pl/11_02.html?brandId=293,导致虽然路由匹配正确,但仍然出现了问号及后面的参数(而这里我是希望生成的链接为:/pl/11_02.html)

 

为了达到这个目的,而又不将Url写死,修改路由配置为:

routes.MapRoute(
name: "ProductList1_01",
url: "pl/{bigSortId}_{smallSortId}_{brandId}.html",
defaults: new { controller = "NewStore", action = "ProductList" },
namespaces: mallNS
);
routes.MapRoute(
name: "ProductList1_02",
url: "pl/{bigSortId}_{smallSortId}.html",
defaults: new { controller = "NewStore", action = "ProductList" ,brandId="" },
namespaces: mallNS
);
routes.MapRoute(
name: "ProductList1_03",
url: "pl/{bigSortId}.html",
defaults: new { controller = "NewStore", action = "ProductList", smallSortId = "", brandId="" },
namespaces: mallNS
);

 

解决此问题。

asp.net mvc 根据路由生成正确的url,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。