我想从 View 绑定(bind)数组以在 Controller 方法中处理它。
生成的 HTML
模型
public class Matrix
{
public int[,] Numbers { get; set; }
}
查看 @model 项目.Models.Matrix
@{
var options = new AjaxOptions()
{
UpdateTargetId = "Matrix",
};
}
@using (Ajax.BeginForm("Form", "Home", FormMethod.Post, options))
{
<div id="Matrix"> </div>
<input type="submit" value="Rotate" name="ButtonType" />
}
局部 View
@model int[,]
@if (Model != null && Model.Length > 0)
{
<table id="numbers-container">
@for (int column = 0; column < Model.GetLength(0); column++)
{
<tr>
@for (int row = 0; row < Model.GetLength(1); row++)
{
var Numbers= Model[column, row];
@Html.TextBoxFor(m => Numbers, new { id = $"{column}_{row}" })
}
</tr>
}
</table>
}
Controller
[HttpPost]
public ActionResult SubmitForm(Matrix model, string ButtonType)
如果我添加一些简单的属性,它填充到模型中,但数组为空,MVC 不想绑定(bind)它,因为生成的 html 中的 id 和名称是相同的。如何更改它以从表单中获取填充数组 Controller ?需要帮助
最佳答案
我尝试重现代码,我更改了 cshtml 文件中的映射,成功了
在CS代码中
public class Matrix
{
public int[][] Numbers { get; set; }
}
public class MatrixController : Controller
{
// GET: Matrix
public ActionResult Index()
{
int col = 2, row = 2;
var matrix = new Matrix();
matrix.Numbers = new int[col][];
for (int i = 0; i < col; i++)
matrix.Numbers[i] = new int[row];
return View(matrix);
}
[HttpPost]
public ActionResult SubmitForm(Matrix matrix, string ButtonType)
{
return null;
}
}
在 cshtml 中
@model WebApplication1.Controllers.Matrix
@{
var options = new AjaxOptions()
{
UpdateTargetId = "Matrix",
};
}
@using (Ajax.BeginForm("SubmitForm", "Matrix", FormMethod.Post, options))
{
<div id="Matrix">
@if (Model != null && Model.Numbers.Length > 0)
{
<table id="numbers-container">
@for (int column = 0; column < Model.Numbers.Length; column++)
{
<tr>
@for (int row = 0; row < Model.Numbers[column].Length; row++)
{
@Html.EditorFor(x => Model.Numbers[column][row])
}
</tr>
}
</table>
}
</div>
<input type="submit" value="Rotate" name="ButtonType" />
}
关于asp.net-mvc - 在 ASP.NET MVC 中绑定(bind)二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56002935/