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?
Another best way is to place Partial View inside shared folder & call same partial View from different controller using Shared Folder. And then call it from controller as mentioned above. That's it.
To return a view from the controller action method, we can use View() method by passing respective parameters. return View(“ViewName”) – returns the view name specified in the current view folder (view extension name “. cshtml” is not required. return View("~/Views/Account/Register.
The shared directory is there specifically to share Views across multiple controllers. Just add your View to the Shared subdirectory and you're good to go. If you do return View("~/Views/Wherever/SomeDir/MyView. aspx") You can return any View you'd like.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With