Pointing all actions without specified view to one concrete view
-
07-12-2019 - |
Question
I am creating advanced site that is based in 99% on one view. I have created the following code which is responsible to point all controllers actions which dont have corresponding view to universal view: ~/Views/Shared/UniversalView.cshtml.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
foreach (IViewEngine engine in ViewEngines.Engines)
{
if (engine is RazorViewEngine)
{
RazorViewEngine razorEngine = (RazorViewEngine)engine;
var locationFormats = razorEngine.ViewLocationFormats;
List<string> l = new List<string>(locationFormats);
l.Add("~/Views/Shared/UniversalView.cshtml");
razorEngine.ViewLocationFormats = l.ToArray();
}
}
}
I am preety sure that there will be much better method to achive that effect. Any ideas?
Solution
You can declare a BaseController and all your controller must inherit from it.
Then just add a method in BaseController like
public ViewResult UniversalView(string viewName="UniversalView")
{
return View(viewName);
}
From other controllers you can call this method instead of traditional View(). If you will specify the view name it will take that view else default is Universal view.
public ActionResult About()
{
return UniversalView();
}
OTHER TIPS
I would just use that view in all the relevant actions:
...
return View("UniversalView");
But if you really want to go your way. Have a look at ExecuteResult method link and use it to achieve what you want.