Asp.net mvc 如何将接口参数传递给RouteValueDictionary()?
在ASP.NET MVC应用程序中,我将一个接口实例作为参数传递。在下面的代码段中,myinterface是接口实例Asp.net mvc 如何将接口参数传递给RouteValueDictionary()?,asp.net-mvc,asp.net-mvc-routing,Asp.net Mvc,Asp.net Mvc Routing,在ASP.NET MVC应用程序中,我将一个接口实例作为参数传递。在下面的代码段中,myinterface是接口实例 return RedirectToAction( "Main", new RouteValueDictionary( new { controller = controllerName, action = "Main", Id = Id, someInterface = myinterface } ) ); 在接收方,该操作如下所示: public ActionRes
return RedirectToAction( "Main", new RouteValueDictionary(
new { controller = controllerName, action = "Main", Id = Id, someInterface = myinterface } ) );
在接收方,该操作如下所示:
public ActionResult Index(Int Id, ISomeInterface someInterface) {...}
我得到以下运行时异常:
无法创建接口的实例
有办法吗?我不知道你的理由是什么。我假设它们是有效的。MVC不会为您的接口提供实现。您必须覆盖默认的模型绑定行为,如下所示,并提供具体类型(它可以来自您的IOC容器): 然后,在应用程序中,Start将如下所示:
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();
}
这是不可能的,除非您使用一个依赖项注入提供程序来告诉实现是什么,或者您为该类型创建了一个ModelBinder,并且ModelBinder决定了实现是什么。像MyBinder这样的类通常会去哪里?自定义路由命名空间或类似的东西?@4thSpace这取决于它。如果从默认模型绑定器继承,我通常将其保留在根目录下。如果我实现IModelBinder接口,通常我喜欢将它们分组到它们自己的空间中。
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();
}