在ASP.NET MVC中绑定二维数组 [英] Binding 2d array in ASP.NET MVC
本文介绍了在ASP.NET MVC中绑定二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要从视图绑定数组,以便在控制器方法中处理它。
已生成的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" />
}
部分视图
@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>
}
控制器
[HttpPost]
public ActionResult SubmitForm(Matrix model, string ButtonType)
如果我添加一些简单的属性,它填充在模型中,但数组为空,MVC不想绑定它,因为生成的html中的ID和名称相同。如何将其从控制器中的Form更改为填充的数组?需要任何帮助
推荐答案
我尝试重新生成代码,更改了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中绑定二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文