因为标题说我试图将带有选中项目的列表从视图传递给控制器。
这就是我的观点:
@model List<MyApp.Models.MyClassObject>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div>
<form action="" method="post">
<table>
@for (int i = 0; i < Model.Count; i += 3)
{
if (Model.Count - i <= 3) { break; }
else
{
<tr>
<td>
@Html.HiddenFor(Modelitem => Model[i].checked)
@Html.HiddenFor(Modelitem => Model[i].url)
@Html.CheckBoxFor(modelItem => Model[i].checked)
@Html.DisplayFor(modelItem => Model[i].checked)
</td>
<td>
@Html.HiddenFor(Modelitem => Model[i+1].checked)
@Html.HiddenFor(Modelitem => Model[i+1].url)
@Html.CheckBoxFor(modelItem => Model[i + 1].checked)
@Html.DisplayFor(modelItem => Model[i + 1].url)
</td>
<td>
@Html.HiddenFor(Modelitem => Model[i+2].checked)
@Html.HiddenFor(Modelitem => Model[i+2].url)
@Html.CheckBoxFor(modelItem => Model[i + 2].checked)
@Html.DisplayFor(modelItem => Model[i + 2].url)
</td>
</tr>
}
}
</table>
<input type="submit" class="btn btn-primary btn-lg" value="Send" />
</form>
</div>
</body>
</html>
为了解释这一点,我输入了隐藏的字段,希望列表通过后不会为空(就像现在一样)
MyClassObject如下所示:
public class MyClassObject
{
public string url;
public bool checked;
public MyClassObject(string item)
{
url = item;
}
public MyClassObject()
{
}
}
控制器:
[HttpPost]
public ActionResult Something(List<MyClassObject> items)
{
//blabla
}
所以再一次,我的问题是,当我按下提交时,我会收到一个X项目列表(x是页面上显示的项目数量,无论是否选中),并且&#34;已检查&#34;和&#34; url&#34;是默认值(false和null) 谢谢!
答案 0 :(得分:-1)
如图所示转换为IList
@model IList<MyApp.Models.MyClassObject>
和像这样的控制器方法
[HttpPost]
public ActionResult Something(IEnumerable<MyClassObject> items)
{
//blabla
}
使用
@using (Html.BeginForm())
{}
而不是表单或将操作赋予表单,因为它将像这样呈现它
<form action="/Controller/Action" method="post"><