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 :-)
Next entry: Strong name access denied error on Windows 7 64-bit from Visual Studio and sn.exe
Previous Entry: Visual Studio 2010 highlighted reference color may cause an issue with non-default color schemes
Latest entries:
Create absolute URLs using ASP.NET MVC
Comments
My Links
Tags
Follow me
About
Powered by FoxBlog
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2011, Nathan Fox