tags:

views:

436

answers:

3

Does anybody know how if it's 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();
    }
}

Thanks.

+1  A: 

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;
Lance Harper
+15  A: 
 private bool ViewExists(string name)
 {
     ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
     return (result.View != null);
 }
Dave Cluderay
This is probably better. I wasn't aware there was a FindView method off of the ViewEngines collection itself.
Lance Harper
Looks like that's going to work. Thanks Dave.
Andrew Hanson
A: 

If you want to re-use this across multiple controller actions, building on the solution given by Dave, you can define a custom view result 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 simply return an instance of your custom view:

public ActionResult Index()
{ 
    return new CustomViewResult();
}
DSO