我的问题是如何从视图中将表数据返回到控制器?
我的模型中有课程:
public class Company
{
public string Name { get; set; }
public int ID { get; set; }
public string Address { get; set; }
public string Town { get; set; }
}
我将公司名单传递给我的观点:
@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" />
}
一切看起来都很好,但我不明白如何在控制器中获取修改后的数据?我使用了这些方法:
public ActionResult Edit(IEnumerable<Company> companies)
{
// but companies is null
// and ViewData.Model also is null
return RedirectToAction("SampleList");
}
我需要访问修改后的对象,我做错了什么?
更新:感谢webdeveloper,我只需要使用“for”循环而不是“foreach”循环。正确的版本是
<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>