ビューの編集モードでテーブルにアイテムのリストを表示しています。列を編集した後、提出したい。しかし、リストをポストバックできません。List<Model>
null を示します。
1 に答える
2
解決策があります。また、アイテムのリストをテーブルに表示し、編集してデータベースに戻す必要がありました。コードを投稿していないため、モデルがどのように見えるかわかりません。そのため、自分のモデルを使用します。シナリオに合わせて変更してください。
このサンプルを非常に基本的なものにします。テーブルに顧客のリストを表示し、各名前の横にチェック ボックスを表示して、顧客を削除するかどうかを選択できます。
私の意見は常に強く型付けされています。私は常にビュー モデルを自分のビューに渡します。私は通常作業しますが、ビューにプロパティIEnumberable
が必要なので、代わりに使用しました。Count
List
public class CustomerViewModel
{
public List<Customer> Customers { get; set; }
}
顧客モデルは次のようになります。
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsDelete { get; set; }
}
コントローラーとアクション メソッドは次のようになります。
public class CustomerController : Controller
{
private readonly ICustomerRepository cusotmerRepository;
public CustomerController(ICustomerRepository cusotmerRepository)
{
this.cusotmerRepository = cusotmerRepository;
}
public ActionResult List()
{
CustomerViewModel viewModel = new CustomerViewModel
{
Customers = customerRepository.GetAll()
};
}
[HttpPost]
public ActionResult List(CustomerViewModel viewModel)
{
// Debug the incoming view model and then you will see that the list is there
// Do whatever you need to do
}
}
顧客オブジェクトのリストができたので、あとはテーブルにデータを入力するだけです。
ビューは次のようになります。
@model YourProject.ViewModels.Customers.CustomerViewModel
@using (Html.BeginForm())
{
<table id="customers-datatable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Customers.Count(); i++)
{
<tr>
<td>
@Html.DisplayFor(x => x.Customers[i].FirstName)
@Html.HiddenFor(x => x.Customers[i].FirstName)
</td>
<td>
@Html.DisplayFor(x => x.Customers[i].LastName)
@Html.HiddenFor(x => x.Customers[i].LastName)
</td>
<td>
@Html.CheckBoxFor(x => x.Customers[i].IsDelete)
@Html.HiddenFor(x => x.Customers[i].Id)
</td>
</tr>
}
</tbody>
</table>
}
テーブルの値を保持する方法を示すチェック ボックスを追加しました。テキスト ボックスを含めるように変更できます。
これが役立つことを願っています。
于 2013-08-02T06:09:31.010 に答える