Querystring Consolidation in ASP.NET MVC

I am using ASP.NET MVC for the first time, and so far everything went fine. However, one small question I was hoping would be someone to advise me.

When a page can perform several tasks, and each of them is processed on the server, evaluating the request values, recommended solutions for creating a request based on requests.

For example, a list of products that the user can sort, print, and filter.

The user is sorting -? sortcolumn = example

User changes page in list -? sortcolumn = example & page = 3

The user performs a filter on the list -? sortcolumn = example & page = 3 & filter = expr

The actionlinks for each of these tasks are completely separate from the others, so I need route values ​​in all Html.ActionLink expressions.

Hoping someone can advise.

+3
source share
3 answers

Thanks for helping the guys. I ended up creating an extension method on UrlHelper to easily create URLs that require all active url / querystring data to be returned. I did this because using stringbuilder would be difficult to start changing URLs based on matches in the routing table.

e.g. / Players / quarterback / 4 or players sortcolumn = quarterback &? page = 4

, , URL URL-, .

using System.Web.Routing;

namespace System.Web.Mvc
{
    public static class UrlHelperExtensions
    {
        public static string RouteUrlIncludingQuerystring(this UrlHelper helper)
        {
            return helper.RouteUrlIncludingQuerystring(new RouteValueDictionary());
        }

        public static string RouteUrlIncludingQuerystring(this UrlHelper helper, object routeValues)
        {
            return helper.RouteUrlIncludingQuerystring(new RouteValueDictionary(routeValues));
        }

        public static string RouteUrlIncludingQuerystring(this UrlHelper helper, RouteValueDictionary routeValues)
        {
            RouteValueDictionary v = new RouteValueDictionary();

            foreach (var kvp in helper.RequestContext.RouteData.Values)
                v[kvp.Key] = kvp.Value;

            foreach (var kvp in helper.RequestContext.RouteData.DataTokens)
                v[kvp.Key] = kvp.Value;

            foreach (var key in helper.RequestContext.HttpContext.Request.QueryString.AllKeys)
                v[key] = helper.RequestContext.HttpContext.Request.QueryString[key];

            foreach (var kvp in routeValues)
                v[kvp.Key] = kvp.Value;

            return helper.RouteUrl(v);
        }
    }
}
+4

, , . , . querystring, .

:

    public ActionResult ProductsBySystemIndex(int manufacturerID, string page, string sortOrder, string filter)
    {
         if (page != null)
         {
             // do something with page
         }
         // etc.
    }
+2

MvcContrib , , , ( , ). , , , .

0
source

Source: https://habr.com/ru/post/1718659/


All Articles