我正在做一个包含List<object>
的表单。必须将此List<object>
发送给控制器,但我不想使用JSON。可能吗?我是否必须使用id="MyField[i]"
或类似的东西进行测试?
以下是目标Razor代码:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Ajout de Critères sur l'audit @Model.idAudit</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@foreach (var item in Model.criteresList)
{
<div class="form-group">
@Html.LabelFor(model => item.nomCritere, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => item.nomCritere, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => item.nomCritere, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => item.libelle, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => item.libelle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => item.libelle, "", new { @class = "text-danger" })
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
和控制器
[HttpPost]
public ActionResult Criteres(CritereViewModel model)
{
// Call BL to save them all
return RedirectToAction("Index");
}
答案 0 :(得分:1)
这个article解释了有关MVC中绑定数组的所有内容
如果您想直接发布表单值,则需要执行以下操作:
@for (var i = 0 ;i < in Model.criteresList.Count();i++)
{
@Html.EditorFor(model => Model.criteresList[i].nomCritere, new { htmlAttributes = new { @class = "form-control" } })
}
答案 1 :(得分:0)
上一个答案是可行的,你说的也有效(id = "MyField [i]"
)你只需要添加对象属性。
@Html.Hidden(string.Format("model.criteresList[{0}].nomCritere", index),someValue)
<select name="model.criteresList[@index].nomCritere" value="someValue">
控制器中的
[HttpPost]
public ActionResult Criteres(CritereViewModel model)
{}