我遇到了同樣的問題,我的解決方案是在服務層創建一個小類,並將數據映射到視圖中的SelectListItem
。示例代碼:
1)在服務層代用類:
public class SelectListItemBase
{
public String Value { get; set; }
public String Text { get; set; }
}
2)視圖模型:
public class FetchWordsIntegrationViewModel
{
public IList<SelectListItemBase> WordTypes { get; private set; }
public FetchWordsIntegrationViewModel()
{
WordTypes = new List<SelectListItemBase>();
WordTypes.Add(new SelectListItemBase() { Value = "0", Text = Constants.Ids.SelectionListDefaultText });
WordTypes.Add(new SelectListItemBase() { Value = ((int)FetchedWordType.ProperNoun).ToString(), Text = "Proper noun" });
// other select list items here
}
}
3)的代碼,在動作
public ActionResult Index()
{
var vm = theService.CreateViewModel();
return View(vm);
}
4 )使用Automapper進行映射(這不是必需的,因爲SelectListItem
可以使用LI很容易地生成NQ)
Mapper.CreateMap<SelectListItemBase, SelectListItem>();
5)最後,從該視圖
@Html.DropDownListFor(m => m.WordTypes,
(IEnumerable<SelectListItem>)Mapper.Map(
Model.WordTypes,
typeof(IList<SelectListItemBase>),
typeof(IList<SelectListItem>))
)
正是由於這一簡單的任務相當迂迴,但允許期望的去耦,也允許容易地圖等性能,如果需要的話代碼。
是的,這是我的問題,其他人是怎麼做的。你如何描述我是如何做到的,但是當SelectListItem返回某種類型時,不需要進行所有轉換。我可以做DropDL.Foo = Repository.SomeListdata而不是havng來轉換所有的時間。我實際上返回IEnumerable,然後再轉換,但我只是想獲得其他想法 –
2011-03-26 19:59:55
@William因此,你最好的選擇是在你的應用程序中有一個FooDropDownService,它從數據存儲獲取你的Foo列表並轉換爲你的DropDownList類型應用。 – Swaff 2011-03-26 20:08:22
這意味着必須爲每個應用程序類型創建一個服務(一般來說,我的服務與存儲庫位於同一個dll中,並且由所有人使用)我想您可以創建您自己的FooSelectListItem類,以便由服務返回並從MVC DLL解耦 – 2011-03-26 20:14:23