Reputation: 1432
I'm using C# Asp.Net MVC and I want to get filters as parameter in my controller action.
I have a query string for filters. It is looks like so:
?page=2&groups%5B0%5D=group1&groups%5B1%5D=group2&category%5B0%5D=category1
How could I parse it to Dictionary<string, List<string>>
?
Or to List<Filter>
?
class Filter
{
public string Name { get; set; }
public List<string> Values { get; set; }
}
Upvotes: 2
Views: 2017
Reputation: 85
This is case of custom model binding. we can create one by inheriting from System.Web.Mvc.IModelBinder
:
public class SearchModelBinder : IModelBinder
{
private NameValueCollection _queryString;
private List<string> GetValues(string key)
{
return (_queryString.GetValues(key) ?? throw new InvalidOperationException()).ToList();
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
_queryString = controllerContext.HttpContext.Request.QueryString;
return _queryString.AllKeys.Select(x => new Filter { Name = x, Values = GetValues(x) }).ToList();
}
}
And then in controller action (notice parameter attribute)
public ActionResult Search([ModelBinder(typeof(SearchModelBinder))] List<Filter> filter)
{
// do something with filter
return Content(filter.LastOrDefault()?.Name);
}
Upvotes: 2
Reputation: 6524
You can simply do this:
Dictionary<string, string> keyValue = new Dictionary<string, string>();
foreach (String key in Request.QueryString.AllKeys)
{
keyValue.Add(key, Request.QueryString[key] ?? string.Empty);
}
Upvotes: 0
Reputation: 45
In any action you already have some kind of query dictionary. Take a look at
HttpContext.Request.Query
It contains property Keys
and related to each key value
Upvotes: 1