mvc dropdown顯示與賦值

 public ActionResult Index()
        {
            List<SelectListItem> items = new List<SelectListItem>();
           items.Add(new SelectListItem { Text = "wenbin", Value = "1" });
           items.Add(new SelectListItem { Text = "duying", Value = "2" });
           items.Add(new SelectListItem { Text = "baby", Value = "3", Selected = true });
           ViewData["register"] = items;

           List<SelectListItem> newItem = new List<SelectListItem>();
           string[] str = ConfigurationManager.AppSettings["test"].Split(',');
           foreach (var m in str) {
               newItem.Add(new SelectListItem { Text = m, Value = m});
           }
           ViewData["newItem"] = newItem;
            return View();
        }

在視圖中可以直接這樣

@Html.DropDownList("register")
@Html.DropDownList("newItem1", (List<SelectListItem>)ViewData["newItem"], new { @class = "from" })

第一個直接把值在list 直接寫出來了,第二個是把值存在web.config中,然後再取出來,數據便於統一管理。

存在web.config中的代碼,就是找到appsetting節點,寫一個add

<appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="test" value="mm,kk,ll" />

  </appSettings>

後期前臺設計人員特殊需要估計dropdown還不能直接在view中用那種寫法,後期再說。。先學個從web.config中取值。

///////////////////////////////////////////////////////////////////////////

各種bug,反正有時候這樣綁定的時候,出現什麼system.string不能Ienumber<>的時候,在post action中在吧那個viewdate在寫一遍

2015年3月4日23:30:57

view:
    @Html.DropDownList("selected", ViewData["TherapeuticArea"] as IEnumerable<SelectListItem>,new { @class = "form-text form-control" })

action
 this.ViewData["TherapeuticArea"] = _commonService.GetSelectList("TA"); ;
            this.ViewData["selected"] = entity.TherapeuticArea;//默認的選中項,前臺dropdown第一個參數就不是name了,而是selected...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章