我被困在ASP.NET MVC5中創建適當的創建/編輯視圖。我有兩個型號Dog
和Human
。一隻狗屬於一個Human
。我正在爲Dog
創建create
和edit
的下拉列表,讓我可以根據該特定的Dog
的名稱選擇Human
。這裏是我的模型:爲ASP.NET MVC5關係創建DropDownList
人:
public class Human
{
public int ID { get; set; }
public string Name { get; set; }
}
犬:
public class Dog
{
public int ID { get; set; }
public string Name { get; set; }
public Human Human { get; set; }
}
我創建行動:
// GET: /Dog/Create
public ActionResult Create()
{
ViewBag.HumanSelection = db.Humen.Select(h => new SelectListItem
{
Value = h.ID.ToString(),
Text = h.Name
});
return View();
}
這裏是我的觀點的相關部分:
<div class="form-group">
@Html.LabelFor(model => model.Human.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Human, ViewBag.HumanSelection);
</div>
</div>
我收到以下錯誤,當我運行此:
Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper<Test.Models.Dog>' has no applicable method named 'DropDownListFor' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
我是新的C#&實體框架。我究竟做錯了什麼?有沒有辦法做到這一點,而無需手動查詢數據庫?像Rails中的集合表單助手一樣? 我跟着一堆教程,既舊或太複雜,我不能遵循。
我不認爲你的問題清楚問題是什麼。你是否收到錯誤? – alan
以下連結可能對您有所幫助。此作品適用於我
http://ilyasmamunbd.blogspot.com/2014/03/how-to-create-dynamic-dropdownlist-step.html –