Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc ASP.NET MVC、Querystring、routes和默认绑定器,如何组合?_Asp.net Mvc_Routing_Strongly Typed View_Request.querystring - Fatal编程技术网

Asp.net mvc ASP.NET MVC、Querystring、routes和默认绑定器,如何组合?

Asp.net mvc ASP.NET MVC、Querystring、routes和默认绑定器,如何组合?,asp.net-mvc,routing,strongly-typed-view,request.querystring,Asp.net Mvc,Routing,Strongly Typed View,Request.querystring,我有一个ASP.NET MVC站点,它使用强类型视图。在我的例子中,控制器操作可能如下所示: public ActionResult List(MyStrongType data) public static class StackOverflowExtensions { public static string UpdateCurrentQueryString(this HtmlHelper helper, object parameters) { var n

我有一个ASP.NET MVC站点,它使用强类型视图。在我的例子中,控制器操作可能如下所示:

public ActionResult List(MyStrongType data)
public static class StackOverflowExtensions
{
    public static string UpdateCurrentQueryString(this HtmlHelper helper, object parameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var propertyInfo in parameters.GetType().GetProperties(BindingFlags.Public))
        {
            newQueryStringNameValueCollection[propertyInfo.Name] = propertyInfo.GetValue(parameters, null).ToString();
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }

    private static string ToQueryString(NameValueCollection nvc)
    {
        return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
    }
}
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new {page = "2", parameter2 = "someValue"})%>'>Some Link</a>
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new Dictionary<string,string>() {
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr], "2" },
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.AnotherParam], "1234" }})%>'>Some Link</a>
提交页面视图时,响应将生成类似以下内容的URL是的,我知道路由可以生成更好的URL:

http://localhost/Ad/List?F.ShowF=0&ALS.CP=30&ALS.L=0&ALS.OB=0&ALS.ST=0&S=&LS.L1=&LS.L2=&CS.C1=32&CS.C2=34&CS.C3=&ALS.ST=0
如果我再次提交页面,我可以看到操作中的数据对象是根据URLDefaultBinder正确设置的

问题是:假设我要添加页面按钮来更改我网站页面上列表的页面,列表将由诸如筛选器、排序器、每页页数等设置控制,这些设置由querystring控制。首先,我需要在URL中包含所有当前查询参数,然后我需要在不篡改其他查询参数的情况下更新页面参数。如何从view/HTML帮助程序生成此URL

当然,我可以手动操作URL字符串,但这将涉及大量工作,而且如果路由发生更改,则很难跟上最新情况,必须有更简单的方法吗?像ASP.NET Request.querystring这样的可以在服务端更改的querystring集合

我希望不涉及这条路线,但我还是发布了迄今为止的一条:

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        "TreeEditing",
        "{controller}/{action}/{name}/{id}",
        new { controller = "MyCategory", action = "Add", name = string.Empty, id = -1 }
    );
问候

编辑1:可以在视图中设置如下查询参数:

<%= url.Action(new {controller="search", action="result", query="Beverages", Page=2})%>
如您所见,其余参数将丢失

当然,我可以在这个操作中添加所有已知参数,但是如果添加或更改任何查询参数,那么要使所有内容保持最新,需要做大量的工作


我已经阅读了这篇文章,但是如何找到问题的答案呢?

如果要在视图的链接中设置查询字符串:

Html.ActionLink("LinkName", "Action", "Controller", new { param1 = value1, param2 = value2 }, ...)

如果要在回发后在浏览器中进行设置,只需在RouteToAction之类的操作中调用Route*,并设置所需的参数键/值。

如果要在视图的链接中设置查询字符串:

Html.ActionLink("LinkName", "Action", "Controller", new { param1 = value1, param2 = value2 }, ...)

如果您想在回发后在浏览器中进行设置,只需在RouteToAction之类的操作中调用Route*,并设置所需的参数键/值。

我觉得您遇到的问题是,您希望能够轻松地保留当前请求中的查询字符串值,并将其呈现到视图中链接的URL中。一种解决方案是创建一个HtmlHelper方法,该方法返回带有一些更改的现有查询字符串。我为HtmlHelper类创建了一个扩展方法,它接受一个对象并将其属性名和值与当前请求中的查询字符串合并,然后返回修改后的querystring。看起来是这样的:

public ActionResult List(MyStrongType data)
public static class StackOverflowExtensions
{
    public static string UpdateCurrentQueryString(this HtmlHelper helper, object parameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var propertyInfo in parameters.GetType().GetProperties(BindingFlags.Public))
        {
            newQueryStringNameValueCollection[propertyInfo.Name] = propertyInfo.GetValue(parameters, null).ToString();
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }

    private static string ToQueryString(NameValueCollection nvc)
    {
        return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
    }
}
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new {page = "2", parameter2 = "someValue"})%>'>Some Link</a>
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new Dictionary<string,string>() {
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr], "2" },
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.AnotherParam], "1234" }})%>'>Some Link</a>
它将循环遍历当前请求中的查询字符串值,并合并在传入的对象上定义的属性中。因此,您的视图代码可能如下所示:

public ActionResult List(MyStrongType data)
public static class StackOverflowExtensions
{
    public static string UpdateCurrentQueryString(this HtmlHelper helper, object parameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var propertyInfo in parameters.GetType().GetProperties(BindingFlags.Public))
        {
            newQueryStringNameValueCollection[propertyInfo.Name] = propertyInfo.GetValue(parameters, null).ToString();
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }

    private static string ToQueryString(NameValueCollection nvc)
    {
        return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
    }
}
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new {page = "2", parameter2 = "someValue"})%>'>Some Link</a>
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new Dictionary<string,string>() {
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr], "2" },
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.AnotherParam], "1234" }})%>'>Some Link</a>
它将成为:

?parameter1=abc&page=2&parameter2=someValue
编辑: 上述实现可能不适用于您描述的查询字符串参数名称的字典查找。下面是一个使用字典而不是对象的实现:

    public static string UpdateCurrentQueryString(this HtmlHelper helper, Dictionary<string, string> newParameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var parameter in newParameters)
        {
            newQueryStringNameValueCollection[parameter.Key] = parameter.Value;
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }
视图将通过对字典进行内联初始化并将其传递给助手函数来调用该函数,如下所示:

public ActionResult List(MyStrongType data)
public static class StackOverflowExtensions
{
    public static string UpdateCurrentQueryString(this HtmlHelper helper, object parameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var propertyInfo in parameters.GetType().GetProperties(BindingFlags.Public))
        {
            newQueryStringNameValueCollection[propertyInfo.Name] = propertyInfo.GetValue(parameters, null).ToString();
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }

    private static string ToQueryString(NameValueCollection nvc)
    {
        return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
    }
}
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new {page = "2", parameter2 = "someValue"})%>'>Some Link</a>
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new Dictionary<string,string>() {
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr], "2" },
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.AnotherParam], "1234" }})%>'>Some Link</a>

在我看来,您遇到的问题是希望能够轻松持久化当前请求中的查询字符串值,并将它们呈现到视图中链接的URL中。一种解决方案是创建一个HtmlHelper方法,该方法返回带有一些更改的现有查询字符串。我为HtmlHelper类创建了一个扩展方法,它接受一个对象并将其属性名和值与当前请求中的查询字符串合并,然后返回修改后的querystring。看起来是这样的:

public ActionResult List(MyStrongType data)
public static class StackOverflowExtensions
{
    public static string UpdateCurrentQueryString(this HtmlHelper helper, object parameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var propertyInfo in parameters.GetType().GetProperties(BindingFlags.Public))
        {
            newQueryStringNameValueCollection[propertyInfo.Name] = propertyInfo.GetValue(parameters, null).ToString();
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }

    private static string ToQueryString(NameValueCollection nvc)
    {
        return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
    }
}
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new {page = "2", parameter2 = "someValue"})%>'>Some Link</a>
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new Dictionary<string,string>() {
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr], "2" },
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.AnotherParam], "1234" }})%>'>Some Link</a>
它将循环遍历当前请求中的查询字符串值,并合并在传入的对象上定义的属性中。因此,您的视图代码可能如下所示:

public ActionResult List(MyStrongType data)
public static class StackOverflowExtensions
{
    public static string UpdateCurrentQueryString(this HtmlHelper helper, object parameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var propertyInfo in parameters.GetType().GetProperties(BindingFlags.Public))
        {
            newQueryStringNameValueCollection[propertyInfo.Name] = propertyInfo.GetValue(parameters, null).ToString();
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }

    private static string ToQueryString(NameValueCollection nvc)
    {
        return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
    }
}
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new {page = "2", parameter2 = "someValue"})%>'>Some Link</a>
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new Dictionary<string,string>() {
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr], "2" },
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.AnotherParam], "1234" }})%>'>Some Link</a>
它将成为:

?parameter1=abc&page=2&parameter2=someValue
编辑: 上述实现可能不适用于您描述的查询字符串参数名称的字典查找。下面是一个使用字典而不是对象的实现:

    public static string UpdateCurrentQueryString(this HtmlHelper helper, Dictionary<string, string> newParameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var parameter in newParameters)
        {
            newQueryStringNameValueCollection[parameter.Key] = parameter.Value;
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }
视图将通过对字典进行内联初始化并将其传递给助手函数来调用该函数,如下所示:

public ActionResult List(MyStrongType data)
public static class StackOverflowExtensions
{
    public static string UpdateCurrentQueryString(this HtmlHelper helper, object parameters)
    {
        var newQueryStringNameValueCollection = new NameValueCollection(HttpContext.Current.Request.QueryString);
        foreach (var propertyInfo in parameters.GetType().GetProperties(BindingFlags.Public))
        {
            newQueryStringNameValueCollection[propertyInfo.Name] = propertyInfo.GetValue(parameters, null).ToString();
        }

        return ToQueryString(newQueryStringNameValueCollection);
    }

    private static string ToQueryString(NameValueCollection nvc)
    {
        return "?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
    }
}
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new {page = "2", parameter2 = "someValue"})%>'>Some Link</a>
<a href='/SomeController/SomeAction<%=Html.GetCurrentQueryStringWithReplacements(new Dictionary<string,string>() {
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr], "2" },
{ QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.AnotherParam], "1234" }})%>'>Some Link</a>

我做了你需要的

我为此创建了一个HTML帮助程序。辅助对象采用与普通辅助对象相同的参数。但是,它保留了URL中的当前值。我为URL帮助器和ActionLink帮助器制作了这两个工具

这将替换:Url.Action

这是助手:

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

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 = RouteValues.MergeRouteValues(r, extra);

            //return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, linktext, action, controller, m, htmlAtts);
            return helper.ActionLink(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);
        }
    }

    public static class UrlwParamsExtensions {
        public static string UrlwParams(this HtmlHelper helper, string action, string controller, object extraRVs) {
            NameValueCollection c = helper.ViewContext.RequestContext.HttpContext.Request.QueryString;

            RouteValueDictionary r = RouteValues.optionalParamters(c);

            RouteValueDictionary extra = new RouteValueDictionary(extraRVs);

            RouteValueDictionary m = RouteValues.MergeRouteValues(r, extra);

            string s = UrlHelper.GenerateUrl("", action, controller, m, helper.RouteCollection, helper.ViewContext.RequestContext, false);
            return s;
        }

        public static string UrlwParams(this HtmlHelper helper, string action) {
            return UrlwParams(helper, action, null, null);
        }

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

        public static string UrlwParams(this HtmlHelper helper, string action, object extraRVs) {
            return UrlwParams(helper, action, null, extraRVs);
        }
    }
}
它是如何工作的

这些调用与Html.ActionLink的调用相同,因此您可以简单地替换它们

该方法执行以下操作:

它从当前URL获取所有可选参数,并将它们放置在RouteValueDictionary中。 它还将htmlattributes放在字典中。 然后它接受您指定的额外RouteValue 每年一次,并将其放入RouteValueDictionary中

然后,关键是合并来自的和手动指定的

这发生在RouteValues类中

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

namespace MVC2_NASTEST {
    public static class RouteValues {

        public static RouteValueDictionary optionalParamters() {
            return optionalParamters(HttpContext.Current.Request.QueryString);
        }

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

        public static RouteValueDictionary MergeRouteValues(this RouteValueDictionary original, RouteValueDictionary newVals) {
            // Create a new dictionary containing implicit and auto-generated values
            RouteValueDictionary merged = new RouteValueDictionary(original);

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

        public static RouteValueDictionary MergeRouteValues(this RouteValueDictionary original, object newVals) {
            return MergeRouteValues(original, new RouteValueDictionary(newVals));
        }
    }
}
这很简单。最后,使用合并的RouteValue创建actionlink。此代码还允许您从URL中删除值

示例:

您的URL是localhost.com/controller/action?id=10&foo=bar。如果在该页面中放置此代码

 <%: Html.ActionLinkwParams("Tekst of url", "Action", new {test="yes"}) %>
将返回元素中的URL:localhost.com/controller/action?id=10&test=yes

我猜这就是你所需要的

如果你还有其他问题,就问吧

额外:

有时,当您重定向到另一个操作时,您也会希望将您的值保存在您的操作中。在我的RouteValues类中,这可以很容易地完成:

 public ActionResult Action(string something, int? somethingelse) {
                    return RedirectToAction("index", routeValues.optionalParamters(Request.QueryString));
 }
如果您还想添加一些可选参数,没问题

 public ActionResult Action(string something, int? somethingelse) {
                    return RedirectToAction("index", routeValues.optionalParamters(Request.QueryString).MergeRouteValues(new{somethingelse=somethingelse}));
 }

我想这几乎涵盖了你所需要的一切。

我做了你所需要的

我为此创建了一个HTML帮助程序。辅助对象采用与普通辅助对象相同的参数。但是,它保留了URL中的当前值。我为URL帮助器和ActionLink帮助器制作了这两个工具

这将替换:Url.Action

这是助手:

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

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 = RouteValues.MergeRouteValues(r, extra);

            //return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, linktext, action, controller, m, htmlAtts);
            return helper.ActionLink(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);
        }
    }

    public static class UrlwParamsExtensions {
        public static string UrlwParams(this HtmlHelper helper, string action, string controller, object extraRVs) {
            NameValueCollection c = helper.ViewContext.RequestContext.HttpContext.Request.QueryString;

            RouteValueDictionary r = RouteValues.optionalParamters(c);

            RouteValueDictionary extra = new RouteValueDictionary(extraRVs);

            RouteValueDictionary m = RouteValues.MergeRouteValues(r, extra);

            string s = UrlHelper.GenerateUrl("", action, controller, m, helper.RouteCollection, helper.ViewContext.RequestContext, false);
            return s;
        }

        public static string UrlwParams(this HtmlHelper helper, string action) {
            return UrlwParams(helper, action, null, null);
        }

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

        public static string UrlwParams(this HtmlHelper helper, string action, object extraRVs) {
            return UrlwParams(helper, action, null, extraRVs);
        }
    }
}
它是如何工作的

这些调用与Html.ActionLink的调用相同,因此您可以简单地替换它们

该方法执行以下操作:

它从当前URL获取所有可选参数,并将它们放置在RouteValueDictionary中。 它还将htmlattributes放在字典中。 然后它获取您手动指定的额外routevalues,并将其放置在RouteValueDictionary中

然后,关键是合并来自的和手动指定的

这发生在RouteValues类中

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

namespace MVC2_NASTEST {
    public static class RouteValues {

        public static RouteValueDictionary optionalParamters() {
            return optionalParamters(HttpContext.Current.Request.QueryString);
        }

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

        public static RouteValueDictionary MergeRouteValues(this RouteValueDictionary original, RouteValueDictionary newVals) {
            // Create a new dictionary containing implicit and auto-generated values
            RouteValueDictionary merged = new RouteValueDictionary(original);

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

        public static RouteValueDictionary MergeRouteValues(this RouteValueDictionary original, object newVals) {
            return MergeRouteValues(original, new RouteValueDictionary(newVals));
        }
    }
}
这很简单。最后,使用合并的RouteValue创建actionlink。此代码还允许您从URL中删除值

示例:

您的URL是localhost.com/controller/action?id=10&foo=bar。如果在该页面中放置此代码

 <%: Html.ActionLinkwParams("Tekst of url", "Action", new {test="yes"}) %>
将返回元素中的URL:localhost.com/controller/action?id=10&test=yes

我猜这就是你所需要的

如果你还有其他问题,就问吧

额外:

有时,当您重定向到另一个操作时,您也会希望将您的值保存在您的操作中。在我的RouteValues类中,这可以很容易地完成:

 public ActionResult Action(string something, int? somethingelse) {
                    return RedirectToAction("index", routeValues.optionalParamters(Request.QueryString));
 }
如果您还想添加一些可选参数,没问题

 public ActionResult Action(string something, int? somethingelse) {
                    return RedirectToAction("index", routeValues.optionalParamters(Request.QueryString).MergeRouteValues(new{somethingelse=somethingelse}));
 }
我想这几乎涵盖了你所需要的一切

如果使用action public ActionResult ListMyStrongType数据,则需要包括所有页面设置页面索引、排序等,。。。作为“MyStrongType”的参数,数据对象将包含视图的所有信息

在视图中,如果需要使用CallMeLaNN的方法生成: Html.actionLinkName,操作,控制器,新{param1=Model.value1,param2=Model.param2,…};。您需要在此处手动设置所有参数,或者创建一个帮助器来帮助您填充URL

您不需要关心地址中包含的当前参数

您可以选择以下路线: routes.MapRoute 习惯, {controller}/{action}/,, 新建{controller=Home,action=Index} ; 将所有参数生成为查询字符串

如果使用action public ActionResult ListMyStrongType数据,则需要包括所有页面设置页面索引、排序等,。。。作为“MyStrongType”的参数,数据对象将包含视图的所有信息

在视图中,如果需要使用CallMeLaNN的方法生成: Html.actionLinkName,操作,控制器,新{param1=Model.value1,param2=Model.param2,…};。您需要在此处手动设置所有参数,或者创建一个帮助器来帮助您填充URL

您不需要关心地址中包含的当前参数

您可以选择以下路线: routes.MapRoute 习惯, {controller}/{action}/,, 新建{controller=Home,action=Index} ; 将所有参数生成为查询字符串


但是,如果url已经包含我需要包含在url中的几个querystring参数,该怎么办?我知道存在哪些参数,但不知道url中未包含哪些参数。可以从帮助器中设置吗?但是如果url已经包含我需要包含在url中的两个querystring参数,该怎么办?我知道存在哪些参数,但不知道url中未包含哪些参数。可以从助手处设置吗?>这看起来很好,我已经构建了一个类似的解决方案,但没有那么花哨;但是有一个问题,在我的例子中,我将查询参数存储在一个共享位置,以便了解页面参数的运行情况:QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr]在这种情况下,返回值将是page。可能吗
能否将此与您的解决方案结合起来?您可能需要发布一些代码,我不确定我是否理解您的要求。>抱歉。querystring包含查询参数right。quary参数可能类似于此页=20。如果查询参数页在许多地方使用,那么如果该查询参数更改名称,将需要一些工作。因此,我将把已知的查询参数存储在像这样的指示库中。queryParamKey是enum。通过编写这本字典[queryParamKey],我将在这种情况下获得一页。你明白了吗?我将许多地方使用的查询参数存储在字典中,以便能够在任何地方更改名称。这在您的解决方案中不起作用。@Jim我添加了一些代码,我认为这些代码可以用于您正在尝试执行的操作。我创建了另一个采用字典的helper方法实现,它应该允许您使用返回参数名的helper类。视图代码会变长一点,因为字典初始化比创建匿名对象要详细一点。>这看起来不错,我已经构建了一个类似的解决方案,但没有那么花哨;但是有一个问题,在我的例子中,我将查询参数存储在一个共享位置,以便了解页面参数的运行情况:QuerystringHandler.Instance.KnownQueryParameters[QuaryParameters.PageNr]在这种情况下,返回值将是page。是否可以将此与您的解决方案结合起来?您可能需要发布一些代码,我不确定我是否理解您的要求。>抱歉。querystring包含查询参数right。quary参数可能类似于此页=20。如果查询参数页在许多地方使用,那么如果该查询参数更改名称,将需要一些工作。因此,我将把已知的查询参数存储在像这样的指示库中。queryParamKey是enum。通过编写这本字典[queryParamKey],我将在这种情况下获得一页。你明白了吗?我将许多地方使用的查询参数存储在字典中,以便能够在任何地方更改名称。这在您的解决方案中不起作用。@Jim我添加了一些代码,我认为这些代码可以用于您正在尝试执行的操作。我创建了另一个采用字典的helper方法实现,它应该允许您使用返回参数名的helper类。视图代码会变长一点,因为字典初始化比创建匿名对象要详细一点。