[英]Binding the dropdownlist to the mvc view
我試圖將下拉列表綁定到來自mvc 6中的數據上下文類的數據集。我編寫了一個函數來獲取填充列表,但無法使用剃刀復制該列表。 到目前為止,這就是我所擁有的。 請注意,我尚未創建模型。 嘗試利用數據庫支架中生成的POCO類。
Layout.cshtml上的功能
@functions{
public List<HSIP.Entities.StateDetails> function1()
{
// protected readonly HSIP.Entities.HSIPContext context;
HSIP.Entities.HSIPContext hsipcontext = new HSIP.Entities.HSIPContext();
List<HSIP.Entities.StateDetails> getstatelist = (from s in hsipcontext.StateDetails
select new HSIP.Entities.StateDetails
{
StateDesc = s.StateDesc,
StateCode = s.StateCode,
StateAbbr = s.StateAbbr
}).ToList();
//SelectList list = new SelectList(getstatelist, "Region", "StateCode", "StateAbbr", "StateDesc");
return getstatelist;
}
}
剃刀語法:
@ Html.DropDownList(“ StateDesc”,@ function1(),“請選擇州名”);
Razor語法引發錯誤:沒有給定與IHTMLHelper.Dropdownlist(字符串,IEnumerable,字符串,對象)的形式參數'htmlattributes'相對應的參數。
有人能指出我正確的方向嗎?
謝謝,哈里
我更喜歡這樣做:
在控制器/模型中:
using System.Web.Mvc;
public List<SelectListItem> DropdownListFilter()
{
var listitem = new List<SelectListItem>();
listitem.Add(new SelectListItem { Text = "Dropdown1", Value = "0", Selected = true });
listitem.Add(new SelectListItem { Text = "Dropdown2", Value = "1", Selected = false });
listitem.Add(new SelectListItem { Text = "Dropdown3", Value = "2", Selected = false });
return listitem;
}
當我加載ActionResult時,只需添加以下行:
ViewBag.FilterDropdown = ar.DropdownListFilter().ToList();
在視圖中,您必須像這樣調用Filter下拉列表:
@Html.DropDownList("FilterDropdown")
希望能有所幫助。
首先在控制器中使用SelectListItem並將其傳遞給視圖,然后以Razor語法使用它填充下拉列表。
List<SelectListItem> stateList = (from s in hsipcontext.StateDetails
select new HSIP.Entities.StateDetails
{
StateDesc = s.StateDesc,
StateCode = s.StateCode,
StateAbbr = s.StateAbbr
}).ToList();
視圖:
@Html.DropDownListFor("StateDesc", stateList ,"Please select State Name")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.