0

Here is what I have in my controller:

        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");

My view:

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

But, my class Category has a property named idParent. I want the dropdown to be field with values like this: ParentName -> CategoryName

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

I tried like this:

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

but it's not working. Do you have any idea?

4

1 回答 1

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");   

您可能需要根据您的需要调整此代码,但它应该会给您这个想法。

于 2012-04-08T19:20:58.290 回答