How to get table data from view is asp.net mvc 4
Solution 1
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
Solution 2
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.
azhidkov
Updated on July 30, 2022Comments
-
azhidkov almost 2 years
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>
-
azhidkov over 11 yearsThanks, Yannick, but I tried this right now and it doesn't work for me.