In an ASP.NET MVC application, the model is a list of objects. It is used in the view like this:
<h4>Order Acknowledgement Contact(s)</h4>
@foreach (var contact in Model.Where(c => c.Type == "AK").Take(3))
{
<div class="form-group">
<div class="col-md-10">
@Html.EditorFor(c => contact.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(c => contact.Email, "", new { @class = "text-danger" })
</div>
</div>
}
<h4>Shipping Acknowledgement Contact(s)</h4>
@foreach (var contact in Model.Where(c => c.Type == "BK").Take(3))
{
<div class="form-group">
<div class="col-md-10">
@Html.EditorFor(c => contact.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(c => contact.Email, "", new { @class = "text-danger" })
</div>
</div>
}
When the form is submitted, in the controller the List is null.
[HttpPost]
public ActionResult Edit(List<CustomerContact> customerContacts)
{
Is it possible to fix binding and preserve using linq etc?
CodePudding user response:
foreach loop never submits items back to the controller, it can only display items. So you should use only for loop.
So it is a good idea to create a viewmodel
public class ViewModel
{
public List<CustomerContact> Aks {get; set;}
public List<CustomerContact> Bks {get; set;}
{
your get action
var model = new ViewModel
{
Aks= contacts.Where(c => c.Type == "AK").Take(3));
Bks= contacts.Where(c => c.Type == "BK").Take(3));
}
....
return View(model);
post action
public ActionResult Edit(ViewModel model)
and finally view
@model ViewModel
.....
for (var i=0; i< Model.Aks; i )
{
<div class="form-group">
<div class="col-md-10">
@Html.EditorFor(model => model.Aks[i].Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Aks[i].Email, "", new { @class = "text-danger" })
</div>
</div>
}
.... the same for model.Bks