c# - ASP.NET MVC - 创建操作链接保留查询字符串

标签 c# asp.net-mvc razor asp.net-core asp.net-core-mvc

我目前正在为 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/

相关文章:

asp.net-mvc - 当路由包含 .svc 扩展名时,ASP.Net MVC 404 错误

asp.net-mvc - 多个 SharePoint 应用程序指向同一个 MVC 项目

asp.net-mvc - MVC : How to route/sitemap. xml 到 ActionResult?

c# - 在 C# MVC 中验证枚举值。发生部分验证 - 如何更改验证行为?

c# - 用C#写的com server对象能不能在客户端释放的时候立即发现?

c# - 隐藏部分面板C#

c# - 调试时跳过 Debug.WriteLine

c# - 将文件移动到另一个文件夹时,FileInfo.Path 显示值不在预期范围内异常

asp.net-mvc - 如何将 ReportViewer 控件与 Razor 一起使用?

jquery - 使用 @HTML 助手 DropDownList 更新 .html