Take the 2-minute tour ×

I have an MVC app that uses dynamic business objects that are inherited from a parent object type. For example the base class Client might have two sub classes called Vendor and ServiceProvider, and these are all handled by the same controller. I have a partial view that I load on the right side of the page when viewing the client's details called _Aside.cshtml. When I load the client I try to look for a specific Aside first and failing that I load a generic one. Below is what the code looks like.

    @Html.Partial("_" + Model.Type.TypeName + "Aside")
catch (InvalidOperationException ex)

The TypeName property would have the word "Vendor" or "ServiceProvider" in it.

Now this works fine but the problem is I only want it to fail over if the view is not found, It's also failing over when there is an actual InvalidOperationException thrown by the partial view (usually the result of a child action it might call). I've thought about checking against Exception.Message but that seems a bit hackish. Is there some other way I can get the desired result without having to check the Message property or is that my only option at this point?

ex.Message = "The partial view '_ServiceProviderAside' was not found or no view
              engine supports the searched locations. The following locations were
              searched: (... etc)"

UPDATE: This is the method I added to my project based off of Jack's answer.

public static class ViewExtensionMethods
    public static bool ViewExists(this HtmlHelper helper, string viewName)
        if (string.IsNullOrEmpty(viewName)) throw new ArgumentNullException(viewName, "View name cannot be empty");
        var view = ViewEngines.Engines.FindPartialView(helper.ViewContext, viewName);
        return view.View != null;

In my view...

@(Html.ViewExists("_" + Model.Type.TypeName + "Aside") 
    ? Html.Partial("_" + Model.Type.TypeName + "Aside") 
    : Html.Partial("_Aside"))
share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

You could try the FindPartialView method to check if the view exists. Something along these lines might work (untested):

public bool DoesViewExist(string name)
     string viewName = "_" + Model.Type.TypeName + "Aside";
     ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName , null);
     return (viewResult.View != null);

Info on the FindPartialView method for ASP MVC 3

share|improve this answer
That should work actually, I was too focused on handling the error I didn't think to look for the view using the exposed methods of the view engine. I've modified the question to include the code I came up with. –  Yarx Feb 22 '13 at 19:54
add comment

Your Answer


