Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structuring several mostly-static pages in ASP.NET MVC

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.

like image 375
Rei Miyasaka Avatar asked Dec 12 '22 20:12

Rei Miyasaka


1 Answers

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);
    }
}
like image 85
amd Avatar answered Dec 30 '22 22:12

amd