我目前正在为 ASP.NET Core MVC 编写自己的分页列表。
我在创建以下内容时遇到困难:
我想创建一个 UrlHelper 扩展方法: Url.PageLink(int page, int pageSize)
在该扩展方法中,我想返回一个链接,该链接重用 Controller 、操作、查询字符串的所有当前值,此外,它还应该添加/更新页面、查询字符串中的 pageSize 值。
问题: 从哪里获取 UrlHelper 对象中的当前 Controller 和操作? 重建查询字符串的最佳方法是什么? 我可以在这里看到它 url.ActionContext.HttpContext.Request.QueryString... 但我真的必须手动重建它吗?或者是否存在类似 AddQueryStringValue(int key, object value) 的东西?
提前致谢!!! 西蒙
最佳答案
改进Simon的回答:
它可以被称为 @Url.Current(new {page=42, id=5, foo=bar})
它将保留查询字符串并更新/添加提供的值。
public static class UrlHelperExtensions
{
/// <summary>
/// Get current URL with substituted values while preserving query string
/// </summary>
/// <param name="helper"></param>
/// <param name="substitutes">Query string parameters or route data paremers. E.g. new { action="Index", sort = "asc"}</param>
/// <returns></returns>
public static string Current(this IUrlHelper helper, object substitutes)
{
RouteValueDictionary routeData = new RouteValueDictionary(helper.ActionContext.RouteData.Values);
IQueryCollection queryString = helper.ActionContext.HttpContext.Request.Query;
//add query string parameters to the route data
foreach (var param in queryString)
{
if (!string.IsNullOrEmpty(queryString[param.Key]))
{
//rd[param.Key] = qs[param.Value]; // does not assign the values!
routeData.Add(param.Key, param.Value);
}
}
// override parameters we're changing in the route data
//The unmatched parameters will be added as query string.
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(substitutes.GetType()))
{
var value = property.GetValue(substitutes);
if (string.IsNullOrEmpty(value.ToString()))
{
routeData.Remove(property.Name);
}
else
{
routeData[property.Name] = value;
}
}
string url = helper.RouteUrl(routeData);
return url;
}
}
关于c# - ASP.NET MVC - 创建操作链接保留查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42022311/