我正在熟悉 ASP.NET MVC,但我遇到了一些可能微不足道的事情。我有一個名為 ToDoList 的模型,這是一個帶有 ToDoItems 串列的復雜型別:
public class ToDoList
{
public Guid Id {get;set;}
public string Name { get; set; }
public virtual ICollection<ToDoItem> Items {get;set;}
}
public class ToDoItem
{
public int Id { get; set; }
public string Task { get; set; }
public bool IsDone { get; set; }
public virtual ToDoList ToDoList { get; set; }
}
我的帶有表單的詳細資訊頁面如下所示:
@model DataLayer.TomTest.Entities.ToDoList
<h2>@Model.Name</h2>
@using (@Html.BeginForm())
{
@Html.AntiForgeryToken()
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Items.First().Id)
</th>
<th>
@Html.DisplayNameFor(model => model.Items.First().Task)
</th>
<th>
@Html.DisplayNameFor(model => model.Items.First().IsDone)
</th>
</tr>
@foreach (var toDoItem in Model.Items)
{
<tr>
<td>
@toDoItem.Id
</td>
<td>
@Html.EditorFor(model => toDoItem.Task)
</td>
<td>
@Html.EditorFor(model => toDoItem.IsDone, new {htmlAttributes = new {@Style = "margin-left: 10px;"}})
</td>
</tr>
}
</table>
<input type="submit" value="Save" class="btn btn-default"/>
}
這是它發布到的方法:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Details([Bind(Include = "Id,Name,Items")] ToDoList todoList)
{
if (ModelState.IsValid)
{
_context.Entry(todoList).State = EntityState.Modified;
await _context.SaveChangesAsync();
return View();
}
return View();
}
如您所見,我在[Bind]某處閱讀時包含了該屬性,以確保我獲得了正確的屬性。但是,當我對此進行除錯時,僅填充了 Id 屬性,其余的仍然為空。

我能做些什么來解決這個問題?這是視圖中的錯誤嗎?還是可能沒有正確設定物體框架?在此先感謝您的幫助。
uj5u.com熱心網友回復:
模型系結到串列不適用于foreach; 您需要改用for回圈。
對于回圈中沒有編輯器的任何屬性,您還需要隱藏輸入。
@for (int index = 0; index < Model.Items.Count; index )
{
<tr>
<td>
@Html.HiddenFor(m => m.Items[index].Id)
@Model.Items[index].Id
</td>
<td>
@Html.EditorFor(m => m.Items[index].Task)
</td>
<td>
@Html.EditorFor(m => m.Items[index].IsDone, new { htmlAttributes = new { @Style = "margin-left: 10px;" } })
</td>
</tr>
}
用于模型系結到陣列、串列、集合、字典的 ASP.NET 有線格式 - Scott Hanselman 的博客
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417751.html
標籤:
上一篇:使用Linq查詢c#中的條件從級聯DropDownList中的多個串列中選擇
下一篇:無法創建物體框架代碼優先遷移
