将对象列表发送到控制器而不使用 JSON
本文关键字:JSON 控制器 对象 列表 | 更新日期: 2023-09-27 18:31:06
我正在做一个包含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");
}
好吧,
本文解释了有关MVC中绑定数组的所有内容
如果您想徒手发布表单值,则需要执行以下操作:
@for (var i = 0 ;i < in Model.criteresList.Count();i++)
{
@Html.EditorFor(model => Model.criteresList[i].nomCritere, new { htmlAttributes = new { @class = "form-control" } })
}
前面的答案是可行的,你说的也有效(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)
{}