Reputation: 1077
My question is how to get table data back to the controller from view?
I have class in my model:
public class Company
{
public string Name { get; set; }
public int ID { get; set; }
public string Address { get; set; }
public string Town { get; set; }
}
and I pass list of Companies to my view as:
@model IEnumerable<MyTestApp.Web.Models.Company>
....
@using (Html.BeginForm("Edit", "Shop"))
{
<table id="example">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Town)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.EditorFor(modelItem => item.Name)
</td>
<td>
@Html.EditorFor(modelItem => item.Address)
</td>
<td>
@Html.EditorFor(modelItem => item.Town)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Submit" />
}
And everything looks ok, but I can't understand how to get modified data in the controller? I used these approaches:
public ActionResult Edit(IEnumerable<Company> companies)
{
// but companies is null
// and ViewData.Model also is null
return RedirectToAction("SampleList");
}
I need access to modified objects, what am I doing wrong?
UPDATE: Thanks to webdeveloper, I just needed use 'for' loop instead of 'foreach' loop. Right version is
<tbody>
@for (int i = 0; i < Model.Count(); i++ ) {
<tr>
<td>
@Html.EditorFor(modelItem => modelItem[i].Name)
</td>
<td>
@Html.EditorFor(modelItem => modelItem[i].Address)
</td>
<td>
@Html.EditorFor(modelItem => modelItem[i].Town)
</td>
</tr>
}
</tbody>
Upvotes: 3
Views: 13013
Reputation: 19
You need to bind your table rows by providing an id for each one being edited so mvc can bind to it back to the controller. One row of table data example:
@for (var a = 0; a < @Model.Pets.Count; a++)
{
<tr>
<td>
@Html.CheckBoxFor(model => @Model.Pets[a].ChildSelected, new { @id= a + "childSelected" })
</td>
</tr>
Upvotes: 0
Reputation: 17288
Please, look at my answer here: Updating multiple items within same view OR for Darin Dimitrov answer.
You need items with index
in name
attribute in rendered html markup. Also you could look at: Model Binding To A List
Upvotes: 2
Reputation: 9621
I think that you are missing the Company
's ID in your form so that the model can be correctly bound.
You should add it like this:
@using (Html.BeginForm("Edit", "Shop"))
{
<table id="example">
<thead>
<tr>
<th>
@Html.HiddenFor(model => model.ID)
@Html.DisplayNameFor(model => model.Name)
</th>
...
Otherwise the rest of your code seems to be OK.
Upvotes: 1