Interface issue in MVC 5 "Unable to instantiate interface"
Hi, I am trying to use interfaces in my MVC 5 project with the code below:
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);
}
&
interface
public interface IAccountController
{
languageSetting[] languageSettingMethod();
ID[] IDMethod();
}
However, I am getting the error:
Unable to instantiate interface.
Why is this happening and how can I fix it?
+3
user3894984
source
to share
2 answers
When MVC controllers are called via any route, the binding device tries to find the zero CTOR of this parameter and initialize this object before entering the controller action method. Interfaces cannot be instantiated as they do not have a zero CTOR ... You can change the parameter type to a specific class that implements that interface if you are not hard-coded.
OR here's an example of binding a custom model
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; }
}
}
+3
source to share