MVC控制器.执行区域 [英] MVC controller.Execute with areas

查看:86
本文介绍了MVC控制器.执行区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC4中有一个使用区域的网站.在某些区域(我们称其为Area),我有一个执行此操作的控制器(Controller):

I've a site in MVC4 using areas. In some area (lets call it Area), I have a controller (Controller) with this actions:

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

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

如果我像这样简单地重定向到Area/Controller/OtherAction,这将非常有用:

This works great if I make a simple redirect to Area/Controller/OtherAction like this:

return RedirectToAction("OtherAction", "Controller", new { area = "Area" });

但是我需要(在此处检查原因)进行这样的重定向:

But I need (check here why) to make a redirect like this:

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方法,然后在此代码的最后一行中引发此异常:

And in that case it doesn't work. After the last line, the OtherAction method is executed and then in the last line of this code it throws this exception:

找不到视图索引"或其主视图,或者没有视图引擎 支持搜索的位置.以下位置是 搜索:

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.aspx

〜/Views/Controller/Index.ascx

~/Views/Controller/Index.ascx

〜/Views/Shared/Index.aspx

~/Views/Shared/Index.aspx

〜/Views/Shared/Index.ascx

~/Views/Shared/Index.ascx

〜/Views/Controller/Index.cshtml

~/Views/Controller/Index.cshtml

〜/Views/Controller/Index.vbhtml

~/Views/Controller/Index.vbhtml

〜/Views/Shared/Index.cshtml

~/Views/Shared/Index.cshtml

〜/Views/Shared/Index.vbhtml

~/Views/Shared/Index.vbhtml

为什么会这样,我该如何解决?

Why is this happening and how can I fix it?

推荐答案

您会收到异常,因为ASP.NET MVC尝试在根"上下文中而不是在区域视图目录中查找视图,因为您未设置在routeData中正确地调整区域.

You get the exception because ASP.NET MVC tries to look up your view in the "root" context and not inside the area view directory because you are not setting up the area correctly in the routeData.

area键需要在DataTokens集合中设置,而不是在Values

The area key needs to be set in the DataTokens collections and not in the Values

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

这篇关于MVC控制器.执行区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆