How to create an ASP.NET MVC controller that accepts an unlimited number of parameters from a query string

Example HTTP URL _ // host / URL / unlimited / index first = value1 &? second = value2 ... & anyvalidname = SomeValue

I want one action to take an unknown number of parameters with unknown names in advance. Something like that:

public class UnlimitedController : Controller { public ActionResult Index(object queryParams) { } //or even better public ActionResult Index(Dictionary<string, object> queryParams) { } } 
+4
source share
6 answers

You can create a custom mediator that converts queries into a dictionary.

User model binding

  public class CustomModelBinder: IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var querystrings = controllerContext.HttpContext.Request.QueryString; return querystrings.Cast<string>() .Select(s => new { Key = s, Value = querystrings[s] }) .ToDictionary(p => p.Key, p => p.Value); } } 

Act

 public ActionResult Index([ModelBinder(typeof(CustomModelBinder))] Dictionary<string, string> queryParams) { } 
+4
source

In HomeController.cs

 public ActionResult Test() { Dictionary<string, string> data = new Dictionary<string, string>(); foreach (string index in Request.QueryString.AllKeys) { data.Add(index, Request.QueryString[index]); } StringBuilder sb = new StringBuilder(); foreach (var element in data) { sb.Append(element.Key + ": " + element.Value + "<br />"); } ViewBag.Data = sb.ToString(); return View(); } 

In Test.cshtml

 <h2>Test</h2> @Html.Raw(ViewBag.Data) 

The web page , http://localhost:35268/Home/Test?var1=1&var2=2 , shows:

 var1: 1 var2: 2 
+1
source

why don't you keep everything you want inside one parameter of the query string and get it on the server side as a string
then parse the urself string and get what you want. something like that
http://example.com?a=someVar&b=var1_value1__var2_value2__var3_value3
then on the server side just break the string and get the variables and all the values

if you don’t want this, what you can do is just call the controller via url and manually enter the Request.QueryString[] collection and you will get all the variables and there the values ​​there

0
source

Your controller code might look like

  public ActionResult MultipleParam(int a, int b, int c) { ViewData["Output"] = a + b + c; return View(); } 

Global.asax.cs

 public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Parameter", "{controller}/{action}/{a}/{b}/{c}", new { controller = "Home", action = "MultipleParam", a = 0, b = 0, c = 0 } ); } 

If the route is {controller} / {action} / {id} / {page}, then / Home / MultipleParam / 101/1? showComments = true, then the search engine will look like this:

 public ActionResult MultipleParam(string id /* = "101" */, int page /* = 1 */, bool showComments /* = true */) { } 
0
source

Another possible solution is to create a custom route

 public class ParamsEnabledRoute : RouteBase { private Route route; public ParamsEnabledRoute(string url) { route = new Route(url, new MvcRouteHandler()); } public override RouteData GetRouteData(HttpContextBase context) { var data = route.GetRouteData(context); if (data != null) { var paramName = (string)data.Values["paramname"] ?? "parameters"; var parameters = context.Request.QueryString.AllKeys.ToDictionary(key => key, key => context.Request.QueryString[key]); data.Values.Add(paramName, parameters); return data; } return null; } public override VirtualPathData GetVirtualPath(RequestContext context, RouteValueDictionary rvd) { return route.GetVirtualPath(context, rvd); } } 

Using:

  public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Add(new ParamsEnabledRoute("ParamsEnabled/{controller}/{action}/{paramname}")); } 

Controller:

 public class HomeController : Controller { public ActionResult Test(Dictionary<string, string> parameters) { } } 

URL:

 http://localhost/ParamsEnabled/Home/Test/parameteres?param1=value1&param2=value2 

Route Attribute:

 public class RouteDataValueAttribute : ActionMethodSelectorAttribute { private readonly RouteDataValueAttributeEnum type; public RouteDataValueAttribute(string valueName) : this(valueName, RouteDataValueAttributeEnum.Required) { } public RouteDataValueAttribute(string valueName, RouteDataValueAttributeEnum type) { this.type = type; ValueName = valueName; } public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { if (type == RouteDataValueAttributeEnum.Forbidden) { return controllerContext.RouteData.Values[ValueName] == null; } if (type == RouteDataValueAttributeEnum.Required) { return controllerContext.RouteData.Values[ValueName] != null; } return false; } public string ValueName { get; private set; } } public enum RouteDataValueAttributeEnum { Required, Forbidden } 
0
source

Just use the HttpContext to collect the query string.

 using System.Web; public class UnlimitedController : Controller { public ActionResult Index(object queryParams) { } //or even better public ActionResult Index() { NameValueCollection queryString = HttpContext.Request.QueryString; // Access queryString in the same manner you would any Collection, including a Dictionary. } } 

Question: "How to create an ASP.NET MVC controller that accepts an unlimited number of parameters from the query string?" Any controller will accept an unlimited number of parameters as NamedValueCollection .

0
source

All Articles