4thSpace
4thSpace

Reputation: 44352

How to pass interface parameter to RouteValueDictionary()?

In an ASP.NET MVC app, I'm passing an interface instance as a parameter. In the code snippet below, myinterface is the interface instance.

return RedirectToAction( "Main", new RouteValueDictionary( 
    new { controller = controllerName, action = "Main", Id = Id, someInterface = myinterface } ) );

At the recipient side, the action looks like:

public ActionResult Index(Int Id, ISomeInterface someInterface) {...}

I get the following runtime exception:

Cannot create an instance of an interface

Is there some way to do this?

Upvotes: 1

Views: 7794

Answers (1)

Yogiraj
Yogiraj

Reputation: 1982

I dont know what your reasons are. I am assuming they are valid. MVC is not going to provide implementation for your interface. You will have to override the default model binding behavior like below and provide the concrete type (it can come from your IOC container):

public class MyBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext
    , ModelBindingContext bindingContext, Type modelType)
    {
        if (bindingContext.ModelType.Name == "ISomeInterface") 
            return new SomeType();  
      //You can get the concrete implementation from your IOC container

        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

public interface ISomeInterface
{
    string Val { get; set; }
}
public class SomeType : ISomeInterface  
{
    public string Val { get; set; }
}

Then in your Application Start will look something like below:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
       ModelBinders.Binders.DefaultBinder = new MyBinder();
       //Followed by other stuff
    }
}

Here's working actions

public ActionResult About()
{
     ViewBag.Message = "Your application description page.";

     var routeValueDictionary = new RouteValueDictionary()
     {
          {"id",1},
          {"Val","test"}
     };
     return RedirectToAction("Abouts", "Home", routeValueDictionary);            
}

public ActionResult Abouts(int id, ISomeInterface testInterface)
{
    ViewBag.Message = "Your application description page.";
    return View();
}

Upvotes: 2

Related Questions