Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a view exist in ASP.NET MVC?

Tags:

asp.net-mvc

Is it possible to determine if a specific view name exists from within a controller before rendering the view?

I have a requirement to dynamically determine the name of the view to render. If a view exists with that name then I need to render that view. If there is no view by the custom name then I need to render a default view.

I'd like to do something similar to the following code within my controller:

public ActionResult Index() {     var name = SomeMethodToGetViewName();      // The 'ViewExists' method is what I've been unable to find.     if (ViewExists(name))     {         retun View(name);     }     else     {         return View();     } } 
like image 758
Andrew Hanson Avatar asked Jun 03 '09 20:06

Andrew Hanson


People also ask

How many views are there in MVC?

On basis of data transfer mechanism ASP.NET MVC views are categorized as two types, Dynamic view. Strongly typed view.

What is render view in MVC?

A view renders the appropriate UI by using the data that is passed to it from the controller. This data is passed to a view from a controller action method by using the View method. Note. The Views folder is the recommended location for views in the MVC Web project structure.


2 Answers

 private bool ViewExists(string name)  {      ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);      return (result.View != null);  } 

For those looking for a copy/paste extension method:

public static class ControllerExtensions {     public static bool ViewExists(this Controller controller, string name)     {         ViewEngineResult result = ViewEngines.Engines.FindView(controller.ControllerContext, name, null);         return (result.View != null);     } } 
like image 83
Dave Cluderay Avatar answered Oct 03 '22 23:10

Dave Cluderay


What about trying something like the following assuming you are using only one view engine:

bool viewExists = ViewEngines.Engines[0].FindView(ControllerContext, "ViewName", "MasterName", false) != null; 
like image 41
Lance Harper Avatar answered Oct 03 '22 22:10

Lance Harper