Mathias F
Mathias F

Reputation: 15891

How to pass a list in a get request

I have an url that works for passing a List of strings

/Home/Index?Person%5B0%5D=Myname&Person%5B1%5D=Yourname

Unencoded it is

/Home/Index?Person[0]=Myname&Person[1]=Yourname

The Action Method is

public ActionResult(List<string> person)
 {
...
}

The Parameter List person will be correctly filled with the values Myname and Yourname.

I need to redirect to this url using RedirectToAction

I would usually do

RedirectToAction("Index","Home",new {Parameter1=value1})

But obviously I cant use Person%5B0%5D as a parameter name, because it has ivalid characters.

How can I create such a link or should I use a different URL - scheme?

Upvotes: 0

Views: 2211

Answers (1)

Aravind Goud
Aravind Goud

Reputation: 120

hi i worked on your query and finally got the result just check this code find weather it work with your query.

Controller code :

public ActionResult showString()
        {
            try
            {

                IEnumerable<string> persons = new[] { "myname", "urname" };
                var values = new RouteValueDictionary(
                persons
                    .Select((sampleper, index) => new {sampleper, index })
                    .ToDictionary(
                        key => string.Format("[{0}]", key.index),
                        value => (object)value.sampleper
                    )
            );
            return RedirectToAction("details", values);




            }
            catch (Exception)
            {

                throw;
            }


        }

and another action method is details with list as parameter

public ActionResult details(IEnumerable<string> persons)
        {
             ViewBag.person = persons;



            return View();
        }

it also works if you pass the link as

http://localhost:2266/Home/details?%5B0%5D=myname&%5B1%5D=urname

the view of details action method is

@{
    ViewBag.Title = "details";
}

<h2>details</h2>
<ul>
  @foreach (var i in ViewBag.person)
  { 

  <li>@i</li>


  }

</ul>

Upvotes: 1

Related Questions