Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Pass array object as a route value within Html.ActionLink(...)

Try creating a RouteValueDictionary holding your values. You'll have to give each entry a different key.

<%  var rv = new RouteValueDictionary();
    var strings = GetStringArray();
    for (int i = 0; i < strings.Length; ++i)
    {
        rv["str[" + i + "]"] = strings[i];
    }
 %>

<%= Html.ActionLink( "Link", "Action", "Controller", rv, null ) %>

will give you a link like

<a href='/Controller/Action?str=val0&str=val1&...'>Link</a>

EDIT: MVC2 changed the ValueProvider interface to make my original answer obsolete. You should use a model with an array of strings as a property.

public class Model
{
    public string Str[] { get; set; }
}

Then the model binder will populate your model with the values that you pass in the URL.

public ActionResult Action( Model model )
{
    var str0 = model.Str[0];
}

This really annoyed me so with inspiration from Scott Hanselman I wrote the following (fluent) extension method:

public static RedirectToRouteResult WithRouteValue(
    this RedirectToRouteResult result, 
    string key, 
    object value)
{
    if (value == null)
        throw new ArgumentException("value cannot be null");

    result.RouteValues.Add(key, value);

    return result;
}

public static RedirectToRouteResult WithRouteValue<T>(
    this RedirectToRouteResult result, 
    string key, 
    IEnumerable<T> values)
{
    if (result.RouteValues.Keys.Any(k => k.StartsWith(key + "[")))
        throw new ArgumentException("Key already exists in collection");

    if (values == null)
        throw new ArgumentNullException("values cannot be null");

    var valuesList = values.ToList();

    for (int i = 0; i < valuesList.Count; i++)
    {
        result.RouteValues.Add(String.Format("{0}[{1}]", key, i), valuesList[i]);
    }

    return result;
}

Call like so:

return this.RedirectToAction("Index", "Home")
           .WithRouteValue("id", 1)
           .WithRouteValue("list", new[] { 1, 2, 3 });

Another solution that just came to my mind:

string url = "/Controller/Action?iVal=5&str=" + string.Join("&str=", strArray); 

This is dirty and you should test it before using it, but it should work nevertheless. Hope this helps.


There is a library called Unbinder, which you can use to insert complex objects into routes/urls.

It works like this:

using Unbound;

Unbinder u = new Unbinder();
string url = Url.RouteUrl("routeName", new RouteValueDictionary(u.Unbind(YourComplexObject)));