MVC ActionLink 添加当前 url 中的所有(可选)参数

发布于 2024-09-25 03:04:05 字数 1945 浏览 8 评论 0原文

非常著名的 ActionLink

 <%: Html.ActionLink("Back to List", "Index")%>

现在,这个链接位于我的“详细信息”视图中。索引视图是一个搜索页面。其 URL 如下所示:

http://localhost:50152/2011-2012/Instelling/Details/76?gemeente=Dendermonde&postcode=92**&gebruikerscode=VVKSO114421&dossiernr=114421%20&organisatie=CLB

正如您所看到的,参数数量相当多。显然我想在返回索引页面时保留所有这些参数,因此我需要将它们添加到 ActionLink 中。

现在,我厌倦了手动执行此操作,对于 1 可以,但对于 6 不行。这应该会容易得多。

问题:如何将当前 URL 的所有参数作为可选 RouteValues 返回到 ActionLink 中。

我一直在寻找 Request .QueryString。一定与此有关。我正在考虑在 Global.asax 中编写一些静态方法来完成这项工作,但还没有成功。也许有一种我不知道的简单方法可以做到这一点?

想到的(有效)

编辑:这是我在global.asax:

    public static RouteValueDictionary optionalParamters(NameValueCollection c) {
        RouteValueDictionary r = new RouteValueDictionary();
        foreach (string s in c.AllKeys) {
            r.Add(s, c[s]);
        }
        return r;
    }

Details.aspx:

    <%: Html.ActionLink("Back to List", "Index", MVC2_NASTEST.MvcApplication.optionalParamters(Request.QueryString))%>

我最好将此代码放在哪里?我猜不在 Global.asax 中...

编辑 2:

using System;
using System.Web.Mvc;

namespace MVC2_NASTEST.Helpers {
    public static class ActionLinkwParamsExtensions {
        public static MvcHtmlString CustomLink(this HtmlHelper helper, string linktext) {
            //here u can use helper to get View context and then routvalue dictionary
            var routevals = helper.ViewContext.RouteData.Values;
            //here u can do whatever u want with route values
            return null;
        }

    }
}


<%@ Import Namespace="MVC2_NASTEST.Helpers" %>
...
<%: Html.ActionLinkwParams("Index") %>

The very famous ActionLink:

 <%: Html.ActionLink("Back to List", "Index")%>

Now, this link is in my Details view. The Index view is a search page. The URL of that looks like this:

http://localhost:50152/2011-2012/Instelling/Details/76?gemeente=Dendermonde&postcode=92**&gebruikerscode=VVKSO114421&dossiernr=114421%20&organisatie=CLB

As you can see, quite the amount of parameters. Obviously I want to keep all these parameters when I return to the Index page, so I need to add them in the ActionLink.

Now, I'm tired of doing that manually, it's ok for 1, but not for 6. This should go a lot easier.

Question: How do I return All parameters of the current URL into the ActionLink as optional RouteValues.

I've been looking to Request.QueryString. It has to be something with that. I was thinking of writing some static method in Global.asax doing the job but no luck yet. Maybe there is an easy way to do this which I don't know about?

Edit: This is what I came up with (which works)

In global.asax:

    public static RouteValueDictionary optionalParamters(NameValueCollection c) {
        RouteValueDictionary r = new RouteValueDictionary();
        foreach (string s in c.AllKeys) {
            r.Add(s, c[s]);
        }
        return r;
    }

Details.aspx:

    <%: Html.ActionLink("Back to List", "Index", MVC2_NASTEST.MvcApplication.optionalParamters(Request.QueryString))%>

Where do I best put this code? not in Global.asax I guess...

Edit 2:

using System;
using System.Web.Mvc;

namespace MVC2_NASTEST.Helpers {
    public static class ActionLinkwParamsExtensions {
        public static MvcHtmlString CustomLink(this HtmlHelper helper, string linktext) {
            //here u can use helper to get View context and then routvalue dictionary
            var routevals = helper.ViewContext.RouteData.Values;
            //here u can do whatever u want with route values
            return null;
        }

    }
}


<%@ Import Namespace="MVC2_NASTEST.Helpers" %>
...
<%: Html.ActionLinkwParams("Index") %>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

踏月而来 2024-10-02 03:04:05

这就是我最终修复它的方法,我很自豪,因为它工作得很好而且非常干燥。

视图中的调用:

    <%: Html.ActionLinkwParams("Back to List", "Index")%>

但由于重载,它可以是普通 ActionLink 所采用的任何内容。

助手:

助手从 URL 中获取路由中不存在的所有参数。
例如:这个 url:

http://localhost:50152/2011-2012/myController/Details/77?postalCode=9***&org=CLB

因此它将获取邮政编码和组织并将其放置在新的 ActionLink 中。
通过重载,可以添加其他参数,并且可以删除现有 url 中的参数。

using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace MVC2_NASTEST.Helpers {
    public static class ActionLinkwParamsExtensions {
        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, string controller, object extraRVs, object htmlAttributes) {

            NameValueCollection c = helper.ViewContext.RequestContext.HttpContext.Request.QueryString;

            RouteValueDictionary r = new RouteValueDictionary();
            foreach (string s in c.AllKeys) {
                r.Add(s, c[s]);
            }

            RouteValueDictionary htmlAtts = new RouteValueDictionary(htmlAttributes);

            RouteValueDictionary extra = new RouteValueDictionary(extraRVs);

            RouteValueDictionary m = Merge(r, extra);

            return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, linktext, action, controller, m, htmlAtts);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action) {
            return ActionLinkwParams(helper, linktext, action, null, null, null);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, string controller) {
            return ActionLinkwParams(helper, linktext, action, controller, null, null);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, object extraRVs) {
            return ActionLinkwParams(helper, linktext, action, null, extraRVs, null);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, string controller, object extraRVs) {
            return ActionLinkwParams(helper, linktext, action, controller, extraRVs, null);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, object extraRVs, object htmlAttributes) {
            return ActionLinkwParams(helper, linktext, action, null, extraRVs, htmlAttributes);
        }




        static RouteValueDictionary Merge(this RouteValueDictionary original, RouteValueDictionary @new) {

            // Create a new dictionary containing implicit and auto-generated values
            RouteValueDictionary merged = new RouteValueDictionary(original);

            foreach (var f in @new) {
                if (merged.ContainsKey(f.Key)) {
                    merged[f.Key] = f.Value;
                } else {
                    merged.Add(f.Key, f.Value);
                }
            }

            return merged;

        }
    }

}

在使用重载的视图中:

 <%: Html.ActionLinkwParams("Back to List", "Index","myController", new {testValue = "This is a test", postalCode=String.Empty}, new{ @class="test"})%>

在 URL 中,我的参数 postalCode 具有一些值。我的代码将 URL 中的所有参数设置为 string.Empty,然后从列表中删除此参数。

欢迎提出优化意见或想法。

This is how I finally fixed it, and i'm rather proud because it's working very well and very DRY.

The call in the View:

    <%: Html.ActionLinkwParams("Back to List", "Index")%>

but with the overloads it can be anything which a normal ActionLink takes.

The Helper:

The helper takes all parameters from the url which are not in the route.
For example: this url:

http://localhost:50152/2011-2012/myController/Details/77?postalCode=9***&org=CLB

So it will take the postalCode and the Org and place it in the new ActionLink.
With the overload, additional parameters can be added, and parameters from the existing url can be removed.

using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace MVC2_NASTEST.Helpers {
    public static class ActionLinkwParamsExtensions {
        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, string controller, object extraRVs, object htmlAttributes) {

            NameValueCollection c = helper.ViewContext.RequestContext.HttpContext.Request.QueryString;

            RouteValueDictionary r = new RouteValueDictionary();
            foreach (string s in c.AllKeys) {
                r.Add(s, c[s]);
            }

            RouteValueDictionary htmlAtts = new RouteValueDictionary(htmlAttributes);

            RouteValueDictionary extra = new RouteValueDictionary(extraRVs);

            RouteValueDictionary m = Merge(r, extra);

            return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, linktext, action, controller, m, htmlAtts);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action) {
            return ActionLinkwParams(helper, linktext, action, null, null, null);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, string controller) {
            return ActionLinkwParams(helper, linktext, action, controller, null, null);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, object extraRVs) {
            return ActionLinkwParams(helper, linktext, action, null, extraRVs, null);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, string controller, object extraRVs) {
            return ActionLinkwParams(helper, linktext, action, controller, extraRVs, null);
        }

        public static MvcHtmlString ActionLinkwParams(this HtmlHelper helper, string linktext, string action, object extraRVs, object htmlAttributes) {
            return ActionLinkwParams(helper, linktext, action, null, extraRVs, htmlAttributes);
        }




        static RouteValueDictionary Merge(this RouteValueDictionary original, RouteValueDictionary @new) {

            // Create a new dictionary containing implicit and auto-generated values
            RouteValueDictionary merged = new RouteValueDictionary(original);

            foreach (var f in @new) {
                if (merged.ContainsKey(f.Key)) {
                    merged[f.Key] = f.Value;
                } else {
                    merged.Add(f.Key, f.Value);
                }
            }

            return merged;

        }
    }

}

In the View using overloads:

 <%: Html.ActionLinkwParams("Back to List", "Index","myController", new {testValue = "This is a test", postalCode=String.Empty}, new{ @class="test"})%>

in the URL I have the paramters postalCode with some value. my code takes All of them in the URL, by setting it to string.Empty, I remove this parameter from the list.

Comments or ideas welcome on optimizing it.

合久必婚 2024-10-02 03:04:05

为 Request.QueryString 创建一个 ToRouteValueDictionary() 扩展方法,以按原样使用 Html.ActionLink 并简化视图标记:

<%: Html.ActionLink("Back to List", "Index", Request.QueryString.ToRouteValueDictionary())%>

您的扩展方法可能如下所示:

using System.Web.Routing;
using System.Collections.Specialized;

namespace MyProject.Extensions
{
    public static class CollectionExtensions
    {
        public static RouteValueDictionary ToRouteValueDictionary(this NameValueCollection collection)
        {
            var routeValueDictionary = new RouteValueDictionary();
            foreach (var key in collection.AllKeys)
            {
                routeValueDictionary.Add(key, collection[key]);
            }
            return routeValueDictionary;
        }
    }
}

要在视图中使用扩展方法,请参阅此问题与解答:如何做我在 ASP.NET MVC 视图中使用扩展方法?

这比接受的答案更简单,并且涉及的代码少得多。

Create a ToRouteValueDictionary() extension method for Request.QueryString to use Html.ActionLink as-is and simplify your view markup:

<%: Html.ActionLink("Back to List", "Index", Request.QueryString.ToRouteValueDictionary())%>

Your extension method might look like this:

using System.Web.Routing;
using System.Collections.Specialized;

namespace MyProject.Extensions
{
    public static class CollectionExtensions
    {
        public static RouteValueDictionary ToRouteValueDictionary(this NameValueCollection collection)
        {
            var routeValueDictionary = new RouteValueDictionary();
            foreach (var key in collection.AllKeys)
            {
                routeValueDictionary.Add(key, collection[key]);
            }
            return routeValueDictionary;
        }
    }
}

To use the extension method in your view see this question and answer: How do I use an extension method in an ASP.NET MVC View?

This is simpler and involves much less code than the accepted answer.

荒岛晴空 2024-10-02 03:04:05

这是 ViewContext 的扩展方法,它根据请求路由值和查询字符串创建 RouteValueDictionary。

using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace MyMvcApplication.Utilities
{
    public static class ViewContextExtensions
    {
        /// <summary>
        /// Builds a RouteValueDictionary that combines the request route values, the querystring parameters,
        /// and the passed newRouteValues. Values from newRouteValues override request route values and querystring
        /// parameters having the same key.
        /// </summary>
        public static RouteValueDictionary GetCombinedRouteValues(this ViewContext viewContext, object newRouteValues)
        {
            RouteValueDictionary combinedRouteValues = new RouteValueDictionary(viewContext.RouteData.Values);

            NameValueCollection queryString = viewContext.RequestContext.HttpContext.Request.QueryString;
            foreach (string key in queryString.AllKeys.Where(key => key != null))
                combinedRouteValues[key] = queryString[key];

            if (newRouteValues != null)
            {
                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(newRouteValues))
                    combinedRouteValues[descriptor.Name] = descriptor.GetValue(newRouteValues);
            }


            return combinedRouteValues;
        }
    }
}

您可以将创建的 RouteValueDictionary 传递给 Html.ActionLink 或 Url.Action

@Html.ActionLink("5", "Index", "Product",
    ViewContext.GetCombinedRouteValues(new { Page = 5 }),
    new Dictionary<string, object> { { "class", "page-link" } })

如果请求 URL 中不存在 Page 参数,则会将其添加到生成的 URL 中。如果确实存在,其值将更改为 5。

这篇文章对我的解决方案有更详细的解释。

Here is an extension method for ViewContext that creates a RouteValueDictionary based on the request route values and querystring.

using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace MyMvcApplication.Utilities
{
    public static class ViewContextExtensions
    {
        /// <summary>
        /// Builds a RouteValueDictionary that combines the request route values, the querystring parameters,
        /// and the passed newRouteValues. Values from newRouteValues override request route values and querystring
        /// parameters having the same key.
        /// </summary>
        public static RouteValueDictionary GetCombinedRouteValues(this ViewContext viewContext, object newRouteValues)
        {
            RouteValueDictionary combinedRouteValues = new RouteValueDictionary(viewContext.RouteData.Values);

            NameValueCollection queryString = viewContext.RequestContext.HttpContext.Request.QueryString;
            foreach (string key in queryString.AllKeys.Where(key => key != null))
                combinedRouteValues[key] = queryString[key];

            if (newRouteValues != null)
            {
                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(newRouteValues))
                    combinedRouteValues[descriptor.Name] = descriptor.GetValue(newRouteValues);
            }


            return combinedRouteValues;
        }
    }
}

You can pass the created RouteValueDictionary to Html.ActionLink or Url.Action

@Html.ActionLink("5", "Index", "Product",
    ViewContext.GetCombinedRouteValues(new { Page = 5 }),
    new Dictionary<string, object> { { "class", "page-link" } })

If the Page parameter does not exist in the request URL, it will be added in the generated URL. If it does exist, its value will be changed to 5.

This article has a more detailed explanation of my solution.

ι不睡觉的鱼゛ 2024-10-02 03:04:05
public static class Helpers
    {
        public static MvcHtmlString CustomLink(this HtmlHelper helper,string LinkText, string actionName)
        {
            var rtvals = helper.ViewContext.RouteData.Values;
            var rtvals2 = helper.RouteCollection;
            RouteValueDictionary rv = new RouteValueDictionary();
            foreach (string param in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys) 
            {
                rv.Add(param, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[param]);
            }
            foreach (var k in helper.ViewContext.RouteData.Values) 
            {
                rv.Add(k.Key, k.Value);
            }
            return helper.ActionLink(LinkText, actionName, rv);
        }
    }

我已经测试过这个及其工作原理。可选参数可以从查询字符串中获取
华泰

public static class Helpers
    {
        public static MvcHtmlString CustomLink(this HtmlHelper helper,string LinkText, string actionName)
        {
            var rtvals = helper.ViewContext.RouteData.Values;
            var rtvals2 = helper.RouteCollection;
            RouteValueDictionary rv = new RouteValueDictionary();
            foreach (string param in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys) 
            {
                rv.Add(param, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[param]);
            }
            foreach (var k in helper.ViewContext.RouteData.Values) 
            {
                rv.Add(k.Key, k.Value);
            }
            return helper.ActionLink(LinkText, actionName, rv);
        }
    }

i have tested this and its working. optional parameters can be acquired from query string
HTH

听风吹 2024-10-02 03:04:05

也许最好的方法是编写自己的 html 帮助程序,在其中遍历之前的路由值字典并将路由值添加到当前操作链接,当然操作参数除外。

编辑:
你可以像这样编写 html 帮助器:

public static MvcHtmlString CustomLink(this HtmlHelper helper,string linktext) 
{
    //here you can use helper to get View context and then routvalue dictionary
    var routevals = helper.ViewContext.RouteData.Values;
    //here you can do whatever you want with route values
}

Perhaps the best way is to write your own html helper where you traverse through the previous route value dictionary and add route values to the current action link, except the action parameter off course.

edit:
You can write the html helper like this:

public static MvcHtmlString CustomLink(this HtmlHelper helper,string linktext) 
{
    //here you can use helper to get View context and then routvalue dictionary
    var routevals = helper.ViewContext.RouteData.Values;
    //here you can do whatever you want with route values
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文