私の質問は、テーブル データをビューからコントローラーに戻す方法です。
モデルにクラスがあります:
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のおかげで、「foreach」ループの代わりに「for」ループを使用する必要がありました。正しいバージョンは
<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>