Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

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

I have a method that returns an array (string[]) and I'm trying to pass this array of strings into an Action Link so that it will create a query string similar to:

/Controller/Action?str=val1&str=val2&str=val3...etc

But when I pass new { str = GetStringArray() } I get the following url:

/Controller/Action?str=System.String%5B%5D

So basically it's taking my string[] and running .ToString() on it to get the value.

Any ideas? Thanks!

question from:https://stackoverflow.com/questions/717690/asp-net-mvc-pass-array-object-as-a-route-value-within-html-actionlink

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...