2015-03-31 47 views
1

在ASP.NET MVC應用程序中,我將一個接口實例作爲參數傳遞。在下面的代碼片段中,myinterface是接口實例。如何將接口參數傳遞給RouteValueDictionary()?

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

在收件方,動作看起來像:

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

我得到以下運行時異常:

無法創建接口的實例

有沒有辦法做到這一點?

+0

That's不可能的,除非你使用依賴注入提供商,告訴什麼是執行或您創建該類型和國防部一個模型綁定器資料夾決定什麼是實施。 – 2015-03-31 17:30:06

回答

1

我不知道你的理由是什麼。我假設他們是有效的。 MVC不會爲你的界面提供實現。你將不得不覆蓋默認的模型綁定的行爲像下面提供的具體類型(它可以來自你的IOC容器):

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; } 
} 

然後在你的應用程序開始看起來像下面:

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

這裏的工作行爲

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(); 
} 
+0

像MyBinder這樣的課程通常在哪裏?自定義路由命名空間或類似的東西? – 4thSpace 2015-03-31 20:16:25

+0

@ 4thSpace它取決於我如果從默認模型綁定器繼承,我通常將它保留在根目錄下。如果我實現IModelBinder接口,通常我喜歡將它們分組在自己的空間中。 – Yogiraj 2015-03-31 20:35:56