2010-09-22 50 views
2

我對我的項目使用ASP.NET MVC 2。ASP.NET MVC 2.無法創建接口的實例

我嘗試使用下面的代碼編輯我的產品信息:

[HttpGet] 
    public ActionResult Edit(int id) 
    { 
     IProduct product = productService.getProductById(id); 
     return View(product); 
    } 

IProduct等IEntities使用IoC的溫莎城堡instansing。編輯頁面成功加載。在我的頁面頂部,我聲明該頁面必須Inherits =「System.Web.Mvc.ViewPage 〈 DomainModel.Entities.IProduct 〉。但是,當我嘗試使用下一個代碼更新我的更改時:

[HttpPost] 
    public ActionResult Edit(IProduct product) 
    { 
     //Whatever i did here i always get the error prevents my any actions 
    } 

然後我收到錯誤'無法創建接口的實例。'

任何人都可以解釋,爲什麼? 對不起,可能英文不好,並感謝所有的答案。

回答

5

這是因爲MVC需要知道具體的類型來構建你的產品參數。

無法實例一個IProduct,只是一個實現IProduct的具體類型,最簡單的方法是使用簡單的具體DTO類型來傳輸數據到視圖中(有時稱爲ViewModel)

你可以讓你的例如使用接口類型,如果你實現一個自定義模式l類型的活頁夾。 (基本上是一種告訴MVC在遇到IProduct時實例化哪種類型的方法)。

+1

您是否有這種情況的自定義模型聯編程序的示例? – camainc 2011-09-09 16:54:51