ASP.NET MVC 5 Editor for 2-dimensional array

ぃ、小莉子 提交于 2019-12-06 11:45:05

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!