# Monday, March 15, 2010
« Visual Studio 2010 highlighted reference... | Main | Strong name access denied error on Windo... »
Close up blog entry

I needed some code to determine if an ASP.NET MVC view exists. For a particular controller I’m dynamically determining the view to return by name. I looked at the source code for ASP.NET MVC and figured out how views are found and came up with the following code:

public ActionResult Page(string viewName)
{
   ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);

   if (viewResult.View == null)
   {
      throw new HttpException(404, "404 - View Not Found");
   }

   return View(viewName);
}

This function is a member of a controller class. I wanted to check if the view exists and return a HTTP 404 result if the view is not found. There is likely a better way to wrap up the call in a helper function, but this illustrates the principle.

There may be another or better way to do this, but this works for now and hopefully might help someone else as well :-)

Share/Bookmark
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Live Comment Preview