Might not be a very consequential question, but...
I have a bunch of mostly-static pages: Contact, About, Terms of Use, and about 7-8 more.
Should each of these have their own controllers, or should I just have one action for each?
Thanks in advance.
The best way to add static page to your mvc app is to create a separate controller called Pages
(or whatever you want ) and passing the page name to their Index
method as a parameter.
So you need to test if the page exist before render it, if it exist render it , else render your custom Page Not Found
page.
here is an example :
In 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With