view or no view…that is the question.
I recently ran in to a problem opportunity where some of my pages had a their own template and all generic content pages used their own template. Because they were all routing through the same controller and action I wanted a solution where if a view did not exist for the page in question it would default to the generic view. Here is how i accomplished this.
public ActionResult Page(string viewName) {
ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
if (viewResult.View != null) {
return View(viewName, new PageModel(viewName));
}
else {
// Here you would want to make sure the page exists in your CMS or where ever
return View("Index", new PageModel(viewName));
// If page does not exist you can
// throw new HttpException(404, "404 - View Not Found");
// or
// return View(viewName);
// and add the exception handler below
}
}
Once you check to see if the page exists in your cms or whatever. You can then just return the view that doesn’t exist. But first you must override the controllers exception handler.
protected override void OnException(ExceptionContext filterContext) {
//InvalidOperationException is thrown if the path to the view
// cannot be resolved by the viewengine
if (filterContext.Exception is InvalidOperationException) {
filterContext.ExceptionHandled = true;
filterContext.Result = View("~/Views/Page/NotFound.cshtml");
filterContext.HttpContext.Response.StatusCode = 404;
}
base.OnException(filterContext);
}
There might be cleaner ways and more elegant way to do this so let me know. For now this works for me.
Cheers