问题
I have a model with two-dimensional array in it:
public class Matrix
{
public ValidInt[][] Data;
[Range(0, 8, ErrorMessage = "Введите ширину картины")]
public int Width { get; set; }
[Range(0, 8, ErrorMessage = "Введите ширину картины")]
public int Height { get; set; }
public Matrix(int w, int h)
{
Width = w;
Height = h;
Data = new ValidInt[w][];
for (int i = 0; i < w; i++)
this.Data[i] = new ValidInt[h];
}
public class ValidInt
{
[Range(0, 8, ErrorMessage = "Введите число, соответствующее цвету")]
public int Value { get; set; }
public ValidInt()
{
Value = 0;
}
}
}
Then I would like to have HTML.EditorFor to fill data in each block, so I write something like that:
<table>
@for (int column = 0; column < Model.Data.GetLength(1); column++)
{
<tr>
@for (int row = 0; row < Model.Data.GetLength(0); row++)
{
<td>@Html.EditorFor(x => Model.Data[column, row].Value); </td>
}
</tr>
}
</table>
But turns out you can't have EditorFor for two dimensional arrays. Any ideas on how to bypass that?
回答1:
You cannot use two-dimensional array. However, you could use Jagged Array.
FYI: In order for ModelBinder to bind values to a model, it must have a parameterless constructor.
Model
public class Matrix
{
public int[][] Data { get; set; }
}
View
@using (Html.BeginForm())
{
<table>
@for (int column = 0; column < Model.Data.Length; column++)
{
<tr>
@for (int row = 0; row < Model.Data[column].Length; row++)
{
<td>@Html.EditorFor(x => Model.Data[column][row])</td>
}
</tr>
}
</table>
<button type="submit">Submit</button>
}
Controller
public IActionResult Index()
{
int w = 3, h = 2;
var matrix = new Matrix();
matrix.Data = new int[w][];
for (int i = 0; i < w; i++)
matrix.Data[i] = new int[h];
return View(matrix);
}
[HttpPost]
public IActionResult Index(Matrix matrix)
{
return View(matrix);
}
Result
来源:https://stackoverflow.com/questions/46409152/asp-net-mvc-5-editor-for-2-dimensional-array