我想基于现有路线生成新的URL,但会添加一个新参数'page'
以下是一些示例:
old:〜/ localhost/something?what = 2
new:〜/ localhost/something?what = 2&page = 5
老:〜/ localhost /鞋子
新:〜/ localhost/Shoes/5
我不能只将&page = 5附加到现有网址,因为路由可能不同.
有些使用查询字符串,有些则不使用.
我遇到了类似的问题,并采取了扩展UrlHelper的方法.视图中的代码如下所示:
<a href="<%= Url.AddPage(2) %>">Page 2</a>
Run Code Online (Sandbox Code Playgroud)
UrlHelper扩展名如下:
using System.Web.Mvc;
using System.Web.Routing;
using System.Collections.Specialized;
public static class UrlHelperExtension
{
public static string AddPage(this UrlHelper helper, int page)
{
var routeValueDict = new RouteValueDictionary
{
{ "controller", helper.RequestContext.RouteData.Values["controller"] },
{ "action" , helper.RequestContext.RouteData.Values["action"]}
};
if (helper.RequestContext.RouteData.Values["id"] != null)
{
routeValueDict.Add("id", helper.RequestContext.RouteData.Values["id"]);
}
foreach (string name in helper.RequestContext.HttpContext.Request.QueryString)
{
routeValueDict.Add(name, helper.RequestContext.HttpContext.Request.QueryString[name]);
}
routeValueDict.Add("page", page);
return helper.RouteUrl(routeValueDict);
}
}
Run Code Online (Sandbox Code Playgroud)
几个注释:我检查ID,因为我不在所有路线中使用它.我在最后添加了Page route值,因此它是最后一个url参数(否则你可以在初始构造函数中添加它).
| 归档时间: |
|
| 查看次数: |
4202 次 |
| 最近记录: |