MVC 5中的接口问题'无法创建接口实例'

时间:2014-10-24 08:52:59

标签: c# asp.net-mvc

您好我正在尝试使用以下代码在我的MVC 5项目中使用接口:

public ActionResult Index(IAccountController AccountInterface) 
{
    var DynamicID_DDL = AccountInterface.IDMethod(); 
    var model = new loggedinViewModel
    {
        bIDlistItems = new SelectList(DynamicID_DDL)
    };
    ViewBag.DynamicID_DDL = new List<ID>(DynamicID_DDL);            
    return View(model);
}

&安培;

界面

public interface IAccountController
{
    languageSetting[] languageSettingMethod();
    ID[] IDMethod();
}

然而我收到错误:

无法创建接口的实例。

为什么会发生这种情况,我该如何解决?

2 个答案:

答案 0 :(得分:3)

当通过某种路径调用MVC控制器时,模型绑定器会尝试找到该参数的空CTOR,并在进入控制器操作方法之前初始化该对象。接口无法实例化,因为它们没有空CTOR ......如果您不关心紧耦合,可以将参数类型更改为实现该接口的具体类。

或者这里是关于自定义模型绑定的示例

     public class HomeCustomBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;

            string title = request.Form.Get("Title");
            string day = request.Form.Get("Day");
            string month = request.Form.Get("Month");
            string year = request.Form.Get("Year");

            return new HomePageModels
            {
                Title = title,
                Date = day + "/" + month + "/" + year
            };
        }
        public class HomePageModels {
            public string Title { get; set; }
            public string Date { get; set; }

        }
    }

答案 1 :(得分:-2)

创建一个实现接口的类

Public class AccountController: IAccountController
{

    //Interface Methods
}

在操作方法

中使用class as参数
 public ActionResult Index(AccountController Account) 
  {
        //Your Code
  }