The best way to add a static page to your mvc application is to create a separate controller named Pages (or whatever) and pass the page name to your Index method as a parameter. Therefore, you need to check if the page exists before rendering, if it exists, and also display your custom Page Not Found page. here is an example:
At Global.asax:
// put the StaticPage Rout Above the Default One routes.MapRoute( "StaticPages", "Pages/{page}", new { controller = "Pages", action = "Index"} ); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional} );
Create a controller called PagesController:
public class PagesController : Controller { public ActionResult Index(string page) { // if no paramere was passed call the default page if (string.IsNullOrEmpty(page)) { page = "MyDefaultView"; } // Check if the view exist, if not render the NotfoundView if (!ViewExists(page)) { page = "PageNotFoundView"; } return View(page); } // function that check if view exist private bool ViewExists(string name) { ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null); return (result.View != null); } }
source share