Return a view from a different area
-
30-09-2019 - |
Question
I have my ASP.NET MVC 2 application divided into few areas. One of them is a default area in the main catalog, and the other is an Account
area in the Areas catalog. Now, the problem is that I need to use the same view in controllers from both of these areas.
If they were in the same area, I would just return View("ViewName")
, but what can I do to return a view from my default area in a controller from my Account
area? Any ideas?
Solution
You could specify the relative location of the view:
return View("~/Views/YourArea/YourController/YourView.aspx");
But when a view is shared among multiple areas I would recommend you to use the ~/Views/Shared
folder which serves better this purpose.
OTHER TIPS
This is an old question but still a relevant issue in MVC I think, so here is how I solve it in a DRY fashion that lets you easily change the server path, and have all your dependent actions update automatically:
public class FooController : Controller
{
private ActionResult FooView(string name, string extension = "cshtml") {
return View("~/Areas/Bar/Views/Foo/" + name + "." + extension); }
}
public ActionResult SomeAction(){
return FooView("AreaSpecificViewName");
}
public ActionResult SomeOtherAction(){
return FooView("AnotherAreaSpecificViewName", "aspx");
}
}
This is neat because it defaults to Razor (.cshtml
) View files, but it can be set explicitly by supplying the second parameter, as seen in SomeOtherAction()
.
It's simple but handy, especially during development when the path of your Area might change or something.
Hope that helps someone.