14

I have an array of strings that I need to pass in a query string of Url.Action.

Url.Action("Index", "Resource", new { FormatIds = Model.FormatIDs})

Right now the link is showing up in my browser as System.String[] instead of a query string. Is it possible to have MVC do this automatically with model binding?

I need it to bind with my controller action like:

public ActionResult Index(string[] formatIDs)
3
  • 1
    what do you expect the output to look like? Commented Dec 14, 2012 at 23:17
  • I need it to bind with my controller action that looks like: public ActionResult Index(string[] formatIDs) Commented Dec 14, 2012 at 23:21
  • a query string generally isn't the best way to do this. Commented Dec 14, 2012 at 23:24

3 Answers 3

11

To get the list of string to automatically bind using the default binder, you will need to provide them as:

name=value&name=value2&name=value3

So you'll need to convert your list to something like:

Index?formatIDs=1&formatIDs=2&formatIDs=3
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the default model binder, that is the correct anwser. Very Nice Queti.
This doesn't answer the question. He wants Url.Action to correctly output an array route value to the querystring. He is not asking how to bind such a value.
9

For use the default model binder, you should end up with something like :

Index?formatIDs=value1&formatIDs=value2&formatIDs=value3

you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :

var qs = HttpUtility.ParseQueryString(""); 
new string[] { "value1", "value2", "value3" }.ToList().ForEach(x => qs.Add("formatIDs", x));

Url.Action("Index", "Resource")?@qs

2 Comments

Your suggestion works. But I wonder why it's still so strange and complex to send an array of strings from a razor View to a MVC controller action.
Because normally you should use a form HTML element with get verb and everything will be smooth and simple.
0

There is another way using the RouteValueDictionary with an array:

@{
   var parameters = new RouteValueDictionary();

   for (var i = 0; i < Model.CustomList.Count; ++i)
   {
       parameters.Add($"customListId[{i}]", Model.CustomList[i]);
   }
}

usage:

var url = '@Html.Raw(Url.Action("ControllerActioon", "Controller", parameters))';

Still not very elegant - but working.

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.