2012-07-20 45 views
0

我有以下代碼來生成selectlistitems以顯示在我的下拉列表中。將通用模型添加到幫助類

public static IEnumerable<SelectListItem> ToSelectListItems(this IEnumerable<BlogCategory> categories, int selectedId) 
    { 
     return categories.OrderBy(category => category.Category) 
      .Select(category => new SelectListItem 
      { 
       Selected = (category.ID == selectedId), 
       Text = category.Category, 
       Value = category.ID.ToString() 
      }); 
    } 

我想用這個助手類生成其他列表項然後生成BlogCategory。我怎樣才能做到這一點?

回答

3

你可以做一個基類爲您查找實體:

public class BaseEntity 
{ 
    public int Id {get;set;} 
    public string Title {get;set;} 
} 

public class Category : BaseEntity 
{ 
    //Category fields 
} 

public class Blog : BaseEntity 
{ 
    //Blog fields 
} 

public static IEnumerable<SelectListItem> ToSelectListItems(this IEnumerable<BaseEntity> entityList, int selectedId) 
{ 
    return entityList.OrderBy(q => q.Title) 
     .Select(q => new SelectListItem 
     { 
      Selected = (q.Id == selectedId), 
      Text = q.Title, 
      Value = q.Id.ToString() 
     }); 
} 
+1

efe - 偉大的思想。我正準備發佈我的這個接口而不是基類 – 2012-07-20 13:29:24

+0

其實只是爲了對比... – 2012-07-20 13:34:38

+0

謝謝!這解決了我的問題! – 2012-07-20 14:11:29

2

尤爾根,

基於假設你的意思,其他列表項都符合相同的結構BlogCategory,那麼你可以使用一個接口,而不是輔助工具中的具體類。

這裏是如何可能看:

public static IEnumerable<SelectListItem> ToSelectListItems 
    (this IEnumerable<ICategory> categories, int selectedId) 
{ 
    return categories.OrderBy(category => category.Category) 
     .Select(category => new SelectListItem 
     { 
      Selected = (category.ID == selectedId), 
      Text = category.Category, 
      Value = category.ID.ToString() 
     }); 
} 

享受:

public interface ICategory 
{ 
    int ID { get; set; } 
    string Category { get; set; } 
} 

public class BlogCategory : ICategory 
{ 
    public int ID { get; set; } 
    public string Category { get; set; } 
} 

public class PostCategory : ICategory 
{ 
    public int ID { get; set; } 
    public string Category { get; set; } 
} 

等等,等等。然後用現有的輔助類的線沿線的使用其他類對這個接口的要求...