Is there a view in Asp.Net MVC?

Does anyone know how to determine if a specific view name exists inside the controller before rendering the view?

I have a requirement to dynamically determine the name of a view to render. If a view exists with this name, I need to display that view. If there is no view in the user name, I need to display the default view.

I would like to do something similar to the following code inside 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(); } } 

Thank.

+80
asp.net-mvc
Jun 03 '09 at 20:21
source share
5 answers
  private bool ViewExists(string name) { ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null); return (result.View != null); } 

For those who are looking for an extension method for copy / paste:

 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); } } 
+134
Jun 03 '09 at 20:37
source share

How about trying something like the following, assuming you are using only one viewer:

 bool viewExists = ViewEngines.Engines[0].FindView(ControllerContext, "ViewName", "MasterName", false) != null; 
+15
Jun 03 '09 at 20:34
source share

Here's another [not necessarily recommended] way to do this.

  try { @Html.Partial("Category/SearchPanel/" + Model.CategoryKey) } catch (InvalidOperationException) { } 
+5
May 8 '13 at 23:35
source share

If you want to reuse this for several controller actions, based on the solution given by Dave, you can determine the result of the user view as follows:

 public class CustomViewResult : ViewResult { protected override ViewEngineResult FindView(ControllerContext context) { string name = SomeMethodToGetViewName(); ViewEngineResult result = ViewEngines.Engines.FindView(context, name, null); if (result.View != null) { return result; } return base.FindView(context); } ... } 

Then in your action just return an instance of your custom view:

 public ActionResult Index() { return new CustomViewResult(); } 
+2
Jun 03 '09 at 22:24
source share
 ViewEngines.Engines.FindView(ViewContext.Controller.ControllerContext, "View Name").View != null 

My 2 cents.

0
Jun 16 '15 at 8:20
source share



All Articles