gpt4 book ai didi

redirect - MVC Controller 。使用区域执行

转载 作者:行者123 更新时间:2023-12-04 17:01:42 24 4
gpt4 key购买 nike

我在 MVC4 中有一个使用区域的站点。在某些区域(我们称之为区域),我有一个具有以下操作的 Controller (Controller):

public ActionResult Index()
{
return View();
}

public ActionResult OtherAction()
{
return View("Index");
}

如果我像这样简单地重定向到 Area/Controller/OtherAction,这很有效:
return RedirectToAction("OtherAction", "Controller", new { area = "Area" });

但我需要( check here why )进行这样的重定向:
RouteData routeData = new RouteData();
routeData.Values.Add("area", "Area");
routeData.Values.Add("controller", "Controller");
routeData.Values.Add("action", "OtherAction");
ControllerController controller = new ControllerController();
controller.Execute(new RequestContext(new HttpContextWrapper(HttpContext.ApplicationInstance.Context), routeData));

在这种情况下,它不起作用。在最后一行之后,执行 OtherAction 方法,然后在此代码的最后一行中抛出此异常:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/Controller/Index.aspx

~/Views/Controller/Index.ascx

~/Views/Shared/Index.aspx

~/Views/Shared/Index.ascx

~/Views/Controller/Index.cshtml

~/Views/Controller/Index.vbhtml

~/Views/Shared/Index.cshtml

~/Views/Shared/Index.vbhtml



为什么会发生这种情况,我该如何解决?

最佳答案

您得到异常是因为 ASP.NET MVC 尝试在“根”上下文中而不是在区域 View 目录中查找您的 View ,因为您没有在 routeData 中正确设置区域。 .
area key 需要在DataTokens中设置集合而不是在 Values

RouteData routeData = new RouteData();
routeData.DataTokens.Add("area", "Area");
routeData.Values.Add("controller", "Controller");
routeData.Values.Add("action", "OtherAction");
//...

关于redirect - MVC Controller 。使用区域执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15935069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com