2011-04-20 59 views

回答

5

你可以通過定義視圖模型開始:

public class MyViewModel 
{ 
    public string SelectedItemId { get; set; } 
    public IEnumerable<SelectListItem> Items { get; set; } 
} 

然後控制器將填充此視圖模型(開頭硬編碼一些值只是爲了確保它的工作和y OU有樣機的屏幕展現給您的用戶):

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel 
     { 
      Items = new[] 
      { 
       new SelectListItem { Value = "1", Text = "item 1" }, 
       new SelectListItem { Value = "2", Text = "item 2" }, 
       new SelectListItem { Value = "3", Text = "item 3" }, 
      } 
     }; 
     return View(model); 
    } 
} 

最後一個觀點:

@model MyViewModel 
@Html.DropDownListFor(
    x => x.SelectedItemId, 
    new SelectList(Model.Items, "Value", "Text") 
) 

下一步可以包括爲定義模型,設置此模型的映射,存儲庫讓您與NHibernate取模型,最後調用控制器動作這個倉庫和返回的模型映射到我在示例中使用的視圖模型:

型號:

public class Item 
{ 
    public virtual int Id { get; set; } 
    public virtual string Name { get; set; } 
} 

庫:

public interface IItemsRepository 
{ 
    IEnumerable<Item> GetItems(); 
} 

現在的控制器變爲:

public class HomeController : Controller 
{ 
    private readonly IItemsRepository _repository; 
    public HomeController(IItemsRepository repository) 
    { 
     _repository = repository; 
    } 

    public ActionResult Index() 
    { 
     var items = _repository.GetItems(); 
     var model = new MyViewModel 
     { 
      Items = items.Select(item => new SelectListItem 
      { 
       Value = item.Id.ToString(), 
       Text = item.Name 
      }) 
     }; 
     return View(model); 
    } 
} 

OK,我們正在一點一點在進步不大。現在您可以爲此控制器操作編寫單元測試。

下一步將是實現這個倉庫:

public class ItemsRepositoryNHibernate : IItemsRepository 
{ 
    public IEnumerable<Item> GetItems() 
    { 
     throw new NotImplementedException(
      "Out of the scope for this question. Checkout the NHibernate manual" 
     ); 
    } 
} 

,最後一步是指示你的依賴注入框架來傳遞正確執行庫到HomeController的。例如,如果你使用Ninject所有你需要做的是寫一個模塊,可以配置內核:

public class RepositoriesModule : StandardModule 
{ 
    public override void Load() 
    { 
     Bind<IItemsRepository>().To<ItemsRepositoryNHibernate>(); 
    } 
} 
+0

'+ 1'只是花費超過OP更多的努力,以解決他的問題.. – 2013-05-02 13:42:03