Reputation: 4266
I'm doing a form that contains a List<object>
. This List<object>
must be sent to the controller but I don't want to use JSON. Is it possible? Do I have to test with id="MyField[i]"
or anything like that?
Here is the Razor code that is targeted:
@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>
}
And the Controller
[HttpPost]
public ActionResult Criteres(CritereViewModel model)
{
// Call BL to save them all
return RedirectToAction("Index");
}
Upvotes: 0
Views: 189
Reputation: 1
the previous answer is viable and what you say also works (id = "MyField [i]"
) you just have to add the object properties.
@Html.Hidden(string.Format("model.criteresList[{0}].nomCritere", index),someValue)
<select name="model.criteresList[@index].nomCritere" value="someValue">
in controller
[HttpPost]
public ActionResult Criteres(CritereViewModel model)
{}
Upvotes: 0
Reputation: 12491
Well this article explains everyting about binding arrays in MVC
If you want to post your form values with bare hands you need to do something like this:
@for (var i = 0 ;i < in Model.criteresList.Count();i++)
{
@Html.EditorFor(model => Model.criteresList[i].nomCritere, new { htmlAttributes = new { @class = "form-control" } })
}
Upvotes: 1