如何引用C#输入的HTML?

How to refer to HTML input by C#?

我已经在 .cshtml 文档中编写了这个 C#:

@int[,] grid = new int[81];

for (int i = 0; i < 9; i++)
{
   for (int j = 0; j < 9; j++)
   {
      <input type="text" maxlength="1"/>
   }
}
<button>OK</button>

它创建了一个二维数组'grid'和81个空的html输入框,每个输入框都应该由用户填写一个数字。单击 'OK' 按钮时,'grid' 应该从每个输入元素获取值(例如 grid[0] = '1st input's value', grid[1] = '2nd input's value'...等),但我不知道如何引用每个输入元素以获得它的值,因为每个元素都是由嵌套的 for 循环自动生成的,因此我不能给它一个唯一的 ID 或名称。有什么想法吗?

我不确定你是否可以传递二维数组,但你可以用一维数组传递。

假设您在 Home 控制器中有一个操作 Grid,它接受 int 数组:

public ActionResult Grid(int[] grid)
{
    // do something with grid
}

在您看来,您应该为输入生成名称:

@using (Html.BeginForm("Grid", "Home", FormMethod.Post))
{
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 9; j++)
        {
            <input type="text" maxlength="1" name="grid[@(i*9 + j)]"/>
        }
    }
    <button>OK</button>
}

提交此表单后,您将有 grid 参数填充表单中的值。

使用视图模型来表示您编辑的内容将为您提供双向绑定以及添加客户端和服务器端验证的能力

查看模特

public class Column
{
    [Range(1, 9, ErrorMessage = "Please enter a value between 1 and 9")]
    public int Value { get; set; }
}

public class Row
{
    public Row()
    {
        Columns = Enumerable.Repeat(new Column(), 9).ToList();
    }
    public List<Column> Columns { get; set; }
}

public class Grid
{
    public  Grid()
    {
        Rows = Enumerable.Repeat(new Row(), 9).ToList();
    }
    public List<Row> Rows { get; set; }
}

控制器

public ActionResult Edit()
{
    Grid model = new Grid();
    return View(model);
}

[HttpPost]
public ActionResult Edit(Grid model)
{
    // Get the value of the 3rd column in the 5th row
    int value = model.Rows[2].Columns[4];
}

查看

@model ContractWeb.Controllers.Grid
@using(Html.BeginForm())
{
    for(int i = 0; i < Model.Rows.Count; i++)
    {
        <div>
            @for(int j = 0; j < Model.Rows[i].Columns.Count; j++)
            {
                @Html.TextBoxFor(m => m.Rows[i].Columns[j].Value)
                @Html.ValidationMessageFor(m => m.Rows[i].Columns[j].Value)
            }
        </div>
    }
    <input type="submit" />
}

注意:假设 input 的样式为 inline-block。您还需要考虑验证错误的放置,这样它们的显示就不会搞砸网格布局(也许在一个单独的(嵌套的)循环中所以它们在网格之外?)