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
Remember Me
a@href@title, b, strike
Powered by: newtelligence dasBlog
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Nathan Fox
E-mail