![](/img/trans.png)
[英]Call another controller and use a different Layout for the called controller action MVC ASP.NET
[英]Directly call ASP.NET controller action from a different controller
我有一种情况,我需要重定向到不同控制器中的 ASP.NET MVC 操作。 我不能使用 RedirectToAction,因为我必须 POST 操作的参数以将它们保留在 URL 之外。
我试图像这样直接实例化并调用另一个控制器的操作:
OtherController myOtherController = new OtherController();
myOtherController.ControllerContext = new ControllerContext(this.ControllerContext.RequestContext, myOtherController);
return await myOtherController.Edit(myGuid);
当我这样做时,另一个控制器的代码会执行,但我最终遇到了这个错误:
传递到字典中的模型项的类型为“System.Data.Entity.DynamicProxies.OtherModel_BBCEF7C9378F4C4F097CC08FA2E508B8BD8D865E33093E31959919087A31348E”,但此字典需要“ThisModel”类型的模型项。
有谁知道我是否可以使用当前的方法来完成这项工作? 假设我必须使用 HTTP POST 操作并且 URL 中不能有参数,您是否建议采用不同的方法来实现此结果(除了组合控制器)?
编辑:
请注意,我认为我不能直接从客户端发布,因为我需要嵌套Html.BeginForm
。
您真的应该只是使用 RedirectToAction 将浏览器推送到您想要的操作,而不是尝试这样做。 正如您从@Andrei Olariu 代码中看到的,在构建控制器(DI 然后是上下文和参数映射)的过程中,很多事情发生在幕后,这些事情真的不应该手动完成,并且很容易搞砸,导致浪费数小时的疑惑为什么某些事情没有按预期运行。
我希望我明白你想要做什么。 这是我成功地用来在不同的控制器上执行操作的方法。
private void ExecuteErrorAction(string action, HttpContextWrapper httpContext, Exception exception)
{
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = action;
routeData.Values["exception"] = exception;
IController errorController = DependencyResolver.Current.GetService<ErrorController>();
var context = new RequestContext(httpContext, routeData);
errorController.Execute(context);
}
我认为在您的情况下,这可能如下所示:
private void ExecuteOtherAction(string myGuid, HttpContextWrapper httpContext)
{
var routeData = new RouteData();
routeData.Values["controller"] = "OtherController";
routeData.Values["action"] = "Edit";
routeData.Values["myGuid"] = myGuid;
IController otherCntroller = DependencyResolver.Current.GetService<OtherController>();
var context = new RequestContext(httpContext, routeData);
otherCntroller.Execute(context);
}
这是假设你Edit
的动作OtherController
需要一个称为串myGuid
作为参数。
如果这有帮助,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.