0

I am coding a MVC 5 View, and would like to know how to add data to a hidden 2D array.

Here is my code:

@Html.Hidden("hdnArray")
@for (int i = 0; i < 2; i++)
{
    string[] items = new string[4] { "1", "2", "3", "4" };
    @Html.HiddenFor(items, { id = "hdnArray" })
}

In the above code, I am trying to add the string[] items array to the hidden 2D array called hdnArray.

I am getting many invalid expression errors at the line:

@Html.HiddenFor(items, { id = "hdnArray" })

Can someone please help me with this?

Thanks in advance.

Simon
  • 7,991
  • 21
  • 83
  • 163

1 Answers1

0

You are calling HiddenFor incorrectly. If you want to just add hidden inputs that won't be binded to the model then use:

foreach (var item in new int[] {1, 2, 3, 4, 5})
     {
         @Html.HiddenFor(a => item)
     }

But if you're looking to add this to your Model then you should initialize it in the controller before passing it to the view. Then it can be binded by pointing the expression to Model.ArrayItems:

Model:

public class YourModel{
    public List<int> ArrayItems { get; set; } 
}

View:

foreach (var item in Model.ArrayItems)
     {
         @Html.HiddenFor(a => Model.ArrayItems)
     }
John M
  • 327
  • 3
  • 14