2011-04-05 58 views
2

可能重複:
How can I get this ASP.NET MVC SelectList to work?的DropDownList的SelectList的SelectedValue問題

這到底是什麼呢? MVC3的DropDownList中是否存在某種錯誤? SelectedValue不會在標記中顯示爲實際選定的值。

我正在嘗試不同的方法,沒有什麼作品。

public class SessionCategory 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

public static IEnumerable<SessionCategory> Categories 
{ 
    get 
     { 
      var _dal = new DataLayer(); 
      return _dal.GetSesionCategories(); 
     } 
} 

@{ 
     var cats = Infrastructure.ViewModels.Session.Categories; 
     var sl = new SelectList(cats, "Id", "Name",2); 
} 
@Html.DropDownList("categories", sl); 
+0

你能確認貓變種實際上有類別嗎? – gdp 2011-04-05 15:38:26

回答

6

我認爲你需要使選定的值成爲一個字符串。使用擴展方法還有一些價值,如詳細的here

+0

謝謝!有效 – Agzam 2011-04-05 15:51:07

8

嘗試以下操作:

型號:

public class MyViewModel 
{ 
    public int CategoryId { get; set; } 
    public IEnumerable<SelectListItem> Categories { get; set; } 
} 

控制器:

public ActionResult Foo() 
{ 
    var cats = _dal.GetSesionCategories(); 
    var model = new MyViewModel 
    { 
     // Preselect the category with id 2 
     CategoryId = 2, 

     // Ensure that cats has an item with id = 2 
     Categories = cats.Select(c => new SelectListItem 
     { 
      Value = c.Id.ToString(), 
      Text = c.Name 
     }) 
    }; 
} 

查看:

@Html.DropDownListFor(
    x => x.CategoryId, 
    new SelectList(Model.Categories, "Value", "Text") 
) 
相關問題