-2
我在視圖中以編輯模式顯示錶中的項目列表。編輯完列後,我想提交。但我無法回傳列表。 List<Model>
顯示爲空。在mvc3中回發編輯中的模型列表
我在視圖中以編輯模式顯示錶中的項目列表。編輯完列後,我想提交。但我無法回傳列表。 List<Model>
顯示爲空。在mvc3中回發編輯中的模型列表
我有你的解決方案。我還必須在表格中顯示項目列表,編輯並將其發佈回數據庫。我不知道你的模型是什麼樣子,因爲你沒有發佈任何代碼,所以我將使用我自己的代碼。修改它以適應您的方案。
我打算讓這個示例非常基本。讓我只顯示一個表中的客戶列表,並在每個名稱旁邊都有一個複選框來刪除客戶。
我的意見總是被強制輸入。我總是將視圖模型傳遞給我的觀點。我通常使用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>
}
我只是增加了一個複選框,向您展示如何從表中保留的值。您可以修改它以包含文本框。
我希望這會有所幫助。
代碼丟失。 – gdoron
如果我們看不到您嘗試過的內容,則無法提供幫助。發佈您的代碼。 – Leniency
@SaraCh:如果你不能顯示你已有的東西,不要期待你的問題得到解答。做點什麼,然後我們會提供幫助。 –