今天弄了半天Html.DropDownListFor,更新數據時,老是選不中默認值.爲什麼會這樣.後來研究出來了.原來微軟爲我們簡化流程.當你把強類型model綁定到你的網頁當中,並且model內有值得情況下.他會自動選爲默認值.
從數據庫獲取數據
public class code
{
InvestP2PEntities db = new InvestP2PEntities();
public SelectList getPurposeslist()
{
SelectList mylist = new SelectList(db.BorrowPurposesType,"PurposesTypeId", "PurposesType");
return mylist;
}
}
這裏寫代碼片 cshtml
@Html.DropDownList("BorrowPurposes", new code().getPurposeslist() as SelectList)
//或者下面的方法等於上面的方法
@Html.DropDownListFor(model => model.BorrowPurposes, new code().getPurposeslist(), new { data_val = "false" })
在這裏 如果本頁面是用來創建的,那麼默認的select爲空,就會選取第一項.
如果本頁面是來更新的那麼model裏面會有值,select會自動定位到model裏的該值. 研究了很長時間那.以前沒怎麼用過這個方法.