Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create routeValues (anonymous type) programmatically in ASP.NET MVC 3

Assume we have a page that include some elements to support search from DB, so in Post Action we need to find which elements are active and according to that create route values something like this:

List<Parameter> SearchParameters = GetFilterParameters(collection);


if(SearchParameters.Count > 0)
foreach(Parameter item in SearchParameters) {

    switch(item.Name) {
                    case "Category":
                    CategoryValue= item.Value;
                        break;

                    case "StartDate":
                    StartDateValue= item.Value;
                        break;


                    case "Product":
                    ProductValue= item.Value;
                        break;

                }
return RedirectToAction("Index", new {category = CategoryValue, startdate=StartDateValue, product=ProductValue });

So is there any way to define routeValues dynamically something like the followings Pseudo-Code:

var dynamicRoutValues;
foreach(Parameter item in SearchParameters) {

  dynamicRoutValues.Add(item.Name, item.Value)

}

    return RedirectToAction("Index", dynamicRoutValues);
like image 544
Saeid Avatar asked Apr 21 '12 12:04

Saeid


1 Answers

You can use a RouteValueDictionary:

var dynamicRoutValues = new RouteValueDictionary();
foreach(Parameter item in SearchParameters) {
    dynamicRoutValues[item.Name] = item.Value;
}

return RedirectToAction("Index", dynamicRoutValues);

If SearchParameters implemented IDictionary<string, object> then you could pass it directly to the RouteValueDictionary constructor:

return RedirectToAction("Index", new RouteValueDictionary(SearchParameters));
like image 146
Jon Avatar answered Sep 16 '22 15:09

Jon