In ASP.NET MVC, I\'ve an action which takes user input about rows and columns and then it navigates to the action which generates required number of rows and columns based on th
Create view models that represent what you want to display/edit
public class TableVM
{
public TableVM()
{
Rows = new List();
}
public TableVM(int rows, int columns) : this()
{
for(int i = 0; i < rows; i++)
{
Rows.Add(new RowVM(columns));
}
}
public List Headers { get; set; } // for columns headers
public List Rows { get; set; }
}
public class RowVM
{
public RowVM()
{
Cells = new List();
}
public RowVM(int columns) : this()
{
for(int i = 0; i < columns; i++)
{
Cells.Add(new CellVM());
}
}
public List Cells { get; set; }
}
public class CellVM
{
public string Value { get; set; }
}
and in the GET method, initialize a new TableVM
and return it to the view
TableVM model = new TableVM(5, 5); // 5 x 5 grid
model.Headers = new List{ "col 1", "col 2", "col 3", col 4", "col 5" };
return View(model);
View
@model TableVM
....
@foreach(string header in Model.Headers)
{
@header
}
@for(int r = 0; r < Model.Rows.Count; r++)
{
for (int c = 0; c < Model.Rows[r].Cells.Count; c++)
{
@Html.TextBoxFor(m => m.Rows[r].Cells[c].Value
}
}
Then change you POST method to accept the model
[HttpPost]
public ActionResult Enter(TableVM model)
You can now access each row/column using indexers, for example model.Rows[1].Cells[2].Value
will return the value of the 3rd column in the second row