Search code examples
asp.net-mvc-3razorhidden-field

Storing a list in Hidden field leads to weird results


public ActionResult DoSomething()
{
return View("Index", new IndexModel { Foo = new List<string>() { "*" });
}

where Index.cshtml has a form that contains @Html.HiddenFor(m => m.Foo)

public ActionResult ProcessForm(IndexModel model)
{
}

Inside the ProcessForm your model.Foo contain a single string which reads:

System.Collections.Generic.List`1[System.String]

I am so confused...


Solution

  • That's the result if you run ToString() on your collection, like HiddenFor is doing. You'll need to do something special to make the list into a string.

    Here's a quick and dirty Linq statement that will convert it into a comma-separated list:

    list.Aggregate("", (s,x) => string.IsNullOrEmpty(s) ? x : s + ", " + x);