Create routeValues (anonymous type) programmatical

2020-03-01 18:15发布

问题:

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);

回答1:

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));