我的视图包含很多select
个元素(格式为@Html.DropDownList
或@Html.DropDownListFor
)。问题在于它们以类似table
的方式排列并且双重索引(行数和列数根据数据而变化)。
只能使用单索引属性/字段绑定到DropDownListFor
帮助器的选定值,并且我需要的属性数量会有所不同,所以我想知道:
是否有ASP.NET MVC方法来获取控制器中的选定值?
也就是说,我现在将使用jQuery构建一些(可能是JSON)数据来手动发送到控制器。但首先我想知道是否还有其他我可以尝试的东西:)
示例项目:查看:
@model DropDownMatrixTest.Models.MatrixViewModel
@using (Html.BeginForm("Foo", "Home", FormMethod.Post))
{
<table>
<tbody>
@for (int i = 0; i < 10; i++)
{
<tr>
<td>@i-th row:</td>
@for (int j = 0; j < 4; j++)
{
<td>
@Html.DropDownListFor(m => m.SelectedValues[@i, @j],
Model.Foos.Select(x => new SelectListItem
{
Text = x.Text,
Value = x.Id.ToString()
}))
</td>
}
</tr>
}
</tbody>
</table>
<button type="submit">Submit</button>
}
视图模型:
public class MatrixViewModel
{
public IEnumerable<Foo> Foos { get; set; }
public int[,] SelectedValues { get; set; } // I know this wouldn't work
}
控制器方法:
public ActionResult Index()
{
MatrixViewModel vm = new MatrixViewModel
{
Foos = Enumerable.Range(1, 10).Select(x => new Foo { Id = x, Text = "Foo " + x })
};
return View(vm);
}
[HttpPost]
public ActionResult Foo(MatrixViewModel vm)
{
// Here is where I'd like to get the selected data in some form
return View("Index", vm);
}
答案 0 :(得分:1)
创建视图模型以表示表/矩阵结构
public class CellVM
{
public int SelectedValue { get; set; }
}
public class RowVM
{
public RowVM()
{
Columns = new List<CellVM>();
}
public RowVM(int columns)
{
Columns = new List<CellVM>();
for(int i = 0; i < columns; i++)
{
Columns.Add(new CellVM());
}
}
public List<CellVM> Columns { get; set; }
}
public class MatrixVM
{
public MatrixVM()
{
Rows = new List<RowVM>();
}
public MatrixVM(int columns, int rows)
{
Rows = new List<RowVM>();
for(int i = 0; i < rows; i++)
{
Rows.Add(new RowVM(columns));
}
// initialize collection with the required number of rows
}
public List<RowVM> Rows { get; set; }
public IEnumerable<SelectListItem> Foos { get; set; }
}
在GET方法中,初始化MatrixVM
的新实例并填充SelectList
MatrixVM model = new MatrixVM(4, 4)
{
Foos = Enumerable.Range(1, 10).Select(x => new SelectListItem(){ Value = x.ToString(), Text = "Foo " + x })
};
return View(model);
在视图中
@model MatrixVM
@using (Html.BeginForm())
{
<table>
<tbody>
@for(int r = 0; r < Model.Rows.Count; r++)
{
<tr>
@for(int c = 0; c < Model.Rows[r].Columns.Count; c++)
{
<td>
@Html.DropDownListFor(m => m.Rows[r].Columns[c].SelectedValue, Model.Foos)
</td>
}
</tr>
}
<tbody>
</table>
<input type="submit" />
}
附注:该示例在控制器中创建一个SelectList
,效率高,适用于创建视图,但如果您编辑现有值,则需要生成新的SelectList
并设置由于Selected
在循环中使用时的限制,每次迭代中的DropDownListFor()
属性