9

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 Answer 1

18

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.