2012-04-08 120 views
0

以下是我在我的控制器:下拉列表中的MVC

 Category x = new Category(1, "one", 0); 
     Category y = new Category(2, "two", 1); 


     List<Category> cat = new List<Category>(); 
     cat.Add(x); 
     cat.Add(y); 

     ViewData["categories"] = new SelectList(cat, "id", "name"); 

我的觀點:

<%= Html.DropDownList("categories")%> 

但是,我的班級類別有一個名爲idParent屬性。我想下拉是場這樣的價值觀:ParentName - >類別名稱

public class Category {int idParent, string name, int id} 

我想是這樣的:

ViewData["categories"] = new SelectList(cat, "id", "idParent" + "name"); 

,但它不工作。你有什麼主意嗎?

+0

您是否打開使用強類型視圖? – Shyju 2012-04-08 18:38:32

+0

@Shyju不,我不是。 – 2012-04-08 18:42:01

+0

請通過我的教程http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc http ://blogs.msdn.com/b/rickandy/archive/2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx – RickAndMSFT 2012-04-09 02:36:06

回答

1

將屬性添加到Category類以返回所需的值。

public class Category 
{ 
    int idParent; 
    string name; 
    int id; 

    public Category(int idParent, string name, int id) 
    { 
     this.idParent = idParent; 
     this.name = name; 
     this.id = id; 
    } 

    public string FormattedName 
    { 
     get {return string.format("{0}->{1}", this.idParent, this.name);} 
    } 
} 

那麼你的SelectList構造函數變爲:

ViewData["categories"] = new SelectList(cat, "id", "FormattedName"); 

您可能必須把這個代碼調整您的需求,但它應該給你的想法。