二维数组的ASP.NET MVC 5编辑器 [英] ASP.NET MVC 5 Editor for 2-dimensional array

查看:155
本文介绍了二维数组的ASP.NET MVC 5编辑器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有二维数组的模型:

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;
        }
    }
}

然后,我想使用HTML.EditorFor在每个块中填充数据,因此我编写了这样的内容:

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>

但是事实证明,对于二维数组,您不能拥有EditorFor.关于如何绕开它的任何想法?

But turns out you can't have EditorFor for two dimensional arrays. Any ideas on how to bypass that?

推荐答案

您不能使用二维数组.但是,您可以使用锯齿形阵列.

You cannot use two-dimensional array. However, you could use Jagged Array.

FYI: :为了让ModelBinder将值绑定到模型,它必须具有无参数的构造函数.

FYI: In order for ModelBinder to bind values to a model, it must have a parameterless constructor.

public class Matrix
{
    public int[][] Data { get; set; }
}

查看

@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>
}

控制器

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);
}

结果

这篇关于二维数组的ASP.NET MVC 5编辑器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆