How do I construct a RouteValueDictionary when a route has multiple values?

I am creating a reusable method that validates my model and automatically generates urls (via ActionLink

) for swap. One of the properties of my model is string[]

(for a multi-select picklist), which is fully valid. Example URL-address: https://example.com?user=Justin&user=John&user=Sally

.

However, as the name indicates the type of RouteValueDictionary

implements IDictionary

, so it can not take the same key more than once.

var modelType = model.GetType();
var routeProperties = modelType.GetProperties().Where(p => Attribute.IsDefined(p, typeof(PagingRouteProperty)));

if (routeProperties != null && routeProperties.Count() > 0) {
    foreach (var routeProperty in routeProperties) {
        if (routeProperty.PropertyType == typeof(String)) {
            routeDictionary.Add(routeProperty.Name, routeProperty.GetValue(model, null));
        }

        if (routeProperty.PropertyType == typeof(Boolean?)) {
            var value = (Boolean?)routeProperty.GetValue(model, null);
            routeDictionary.Add(routeProperty.Name, value.ToString());
        }

        //The problem occurs here!
        if (routeProperty.PropertyType == typeof(string[])) {
            var value = (string[])routeProperty.GetValue(model);
            foreach (var v in value) {
                routeDictionary.Add(routeProperty.Name, v);
            }
        }
    }

//Eventually used here
var firstPageRouteDictionary = new RouteValueDictionary(routeDictionary);
firstPageRouteDictionary.Add("page", 1);
firstPageListItem.InnerHtml = htmlHelper.ActionLink("Β«", action, controller, firstPageRouteDictionary, null).ToHtmlString();

      

What can I use to create routes when the key is needed multiple times?

+3


source to share


2 answers


You just need to specify the property name along with the index as Key

:



if (routeProperty.PropertyType == typeof(string[])) {
    var value = (string[])routeProperty.GetValue(model);

    for (var i = 0; i < value.Length; i++) {
        var k = String.Format("{0}[{1}]", routeProperty.Name, i);
        routeDictionary.Add(k, value[i]);
    }
}

      

+5


source


Just try to imagine what the link will look like and it should make sense

new RouteValueDictionary { { "name[0]", "Justin" }, { "name[1]", "John" }, { "name[2]", "Sally" } }

      

which will generate the following query string

Coded



?name%5B0%5D=Justin&name%5B1%5D=John&name%5B3%5D=Sally

      

decoded

?name[0]=Justin&name[1]=John&name[3]=Sally

      

+3


source







All Articles