2012-04-18 97 views
0

我有一個函數可以填充ASP.NET MVC中創建的下拉列表。ASP.NET MVC3 Dropdownlist從不選擇編輯視圖中的值

public static MvcHtmlString countryDropDown(this HtmlHelper helper, string name, string optionLabel, object selectedValue) 
    { 
     XmlDocument doc = new XmlDocument(); 
     doc.Load(HttpContext.Current.Server.MapPath("~/App_Data/countries.xml")); 

     StringBuilder b = new StringBuilder(); 

     b.Append(string.Format("<select name=\"{0}\" id=\"{0}\">", name)); 
     if (!string.IsNullOrEmpty(optionLabel)) 
      b.Append(string.Format("<option value=\"\">{0}</option>", optionLabel)); 

     foreach (XmlNode node in doc.SelectNodes("//country")) 
     { 
      string selected = string.Empty; 
      if (node.Attributes["name"].Value == selectedValue as string) 
      { 
       selected = "selected=\"selected\""; 
      } 
      b.Append(string.Format("<option value=\"{0}\" {2}>{1}</option>", node.Attributes["name"].Value, node.Attributes["name"].Value, selected)); 
     } 
     b.Append("</select>"); 

     return MvcHtmlString.Create(b.ToString()); 
    } 

我用這個功能在創建和編輯意見:

@Html.countryDropDown("Country"," ", ViewData["Country"]) 

這表明國家名單完美,但問題是,我也不會選擇在編輯頁面保存的價值。 如何修改代碼以便它可以在編輯頁面中選擇值。

+1

您是否嘗試過單步執行代碼使用調試器,看看爲什麼你如果失敗了呢? – 2012-04-18 10:47:44

+0

它在selectedValue參數中獲得一個空值。即ViewData [「Country」]發送空。 – hotcoder 2012-04-18 10:49:56

+0

那麼這可能是你的問題 – 2012-04-18 10:50:52

回答

0

使用解決

@Html.countryDropDown("Country"," ", ViewData.Eval("Country")) 

代替

@Html.countryDropDown("Country"," ", ViewData["Country"]