Question

My background is primarily PHP, so i'm used to being able to use deep arrays in forms very easily. What I need is the c#/MVC equivelant of the following:

<input type="text" name="data[0][index_name][0]">
<input type="text" name="data[0][index_name][1]">
<input type="text" name="data[1][index_name][0]">
<input type="text" name="data[1][index_name][1]">
<input type="text" name="data[2][index_name][0][something_else]">
<input type="text" name="data[2][index_name][0]">
<input type="text" name="data[2][index_name][1]">

These could then be accessed in this way in php...

$_POST['data'][0]['index_name'][0];
$_POST['data'][0]['index_name'][1];
$_POST['data'][1]['index_name'][0];
$_POST['data'][1]['index_name'][1];
$_POST['data'][2]['index_name'][0]['something_else'];
$_POST['data'][2]['index_name'][0];
$_POST['data'][2]['index_name'][1];

I've tried looking at/looping over the formColletion object i receive, but the keys are simply the name attribute string, such as "data[2][index_name][0][something_else]," and there is no depth to the data.

How do I parse this data and put in some usable data type? I do not know how deep the array will be as the form changes dynamically on the front end.

So you have some context, this will is being used to build a "table" of data that has a flexible number of rows and columns and each row can be treated as a standard row or grouping row (meaning it contains other rows), so the data can, in theory, get very deep.

On a side note, i've also thought about cleaning up the data on the client side, but it appears there's nothing standard out there that supports this. Jquery.serialize and JQuery.serializeArray() do the same thing as C#/MVC and simply index everything with the full name attribute without taking into account the array indexes.

Thanks for any help!

Was it helpful?

Solution 2

Model Binding turned out to be the correct solution. It support recursion out of the box. Here is a nice write-up: http://msdn.microsoft.com/en-us/magazine/hh781022.aspx

OTHER TIPS

I'm not sure about the deep aspect but if you post items with the same name then MVC reconstructs this as an array.

<input type="hidden" name="MyArray" value="1"/>
<input type="hidden" name="MyArray" value="2"/>
<input type="hidden" name="MyArray" value="3"/>
<input type="hidden" name="MyArray" value="4"/>

And on your controller

[HttpPost]
public ActionResult MyActionMethod(string[] MyArray)
{
  // Do stuff with MyArray
}

You can also access the Request.Form collection in the controller. The key is from the name part of the input on the HTML form.

You can access it like this:

Request.Form["data[2][index_name][0][something_else]"]

Or iterate over it like this:

[HttpPost]
public ActionResult MyActionMethod()
{
  foreach(var key in Request.Form.Keys)
  {
    var item = Request.Form[key];
    // Do stuff with each item
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top