我的项目使用 ASP.NET MVC 2。
我正在尝试使用以下代码编辑我的产品信息:
[HttpGet]
public ActionResult Edit(int id)
{
IProduct product = productService.getProductById(id);
return View(product);
}
IProduct 和其他 IEentities 正在使用 IoC CaSTLe Windsor 进行实例化。编辑页面已成功加载。在页面顶部,我声明该页面必须 Inherits="System.Web.Mvc.ViewPage
[HttpPost]
public ActionResult Edit(IProduct product)
{
//Whatever i did here i always get the error prevents my any actions
}
然后我收到错误“无法创建接口(interface)实例。”
有人能解释一下为什么吗? 抱歉,我的英语可能不好,感谢您的回答。
最佳答案
这是因为 MVC 需要知道为您的产品参数构建的具体类型。
您无法实例化 IProduct,只能实例化实现 IProduct 的具体类型。完成这项工作的最简单方法是使用简单的具体 DTO 类型在 View (有时称为 ViewModel)之间传输数据。
如果您为该类型实现自定义模型绑定(bind)器,则可以使示例与接口(interface)类型一起使用。 (基本上是一种告诉 MVC 在遇到 IProduct 时实例化什么类型的方法)。
关于asp.net-mvc-2 - ASP.NET MVC 2. 无法创建接口(interface)实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3771060/