Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I simplify this code for return views? It seems very redundant

Is there a way to shrink these into just one group result? I have a set of pages like these which simply return static content and thought there must be a more efficient way to do it.

    public ActionResult Research()
    {
        return View();
    }

    public ActionResult Facility()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }

EDIT: Thanks for all the replies :)

like image 716
Travis J Avatar asked Jan 03 '12 21:01

Travis J


2 Answers

You can make a shared action method that takes a viewName parameter:

public ActionResult Show(string viewName)
{
    return View(viewName);
}

You can then route those names to this action:

routes.MapRoute(
    "Simple Content",
    "/{viewName}",
    new { controller = "Something", action = "Show" },
    new { viewName = "Research|Facility|Contact" }
);

The viewName constraint is required to prevent this route from matching arbitrary URLs.

Beware that this is an information disclosure vulnerability; an attacker can request /ControllerName/Show?viewName=~/Views/Secret/View.
If you have any confidential views that don't use models, you should validate the viewName in the action.
To do that, you can use an enum, as in dknaack's answer.

like image 54
SLaks Avatar answered Sep 28 '22 03:09

SLaks


You could create a new route that would take only controllername/{path}, and the path will be your name of the view then in controller action something like this

public ActionResult Page(string path)
{
    return View(path);
}

So going to this path

yourdomain.com/controllername/Ijusttest will load a view from ~/Views/controllername/Ijusttest.cshtml. You just have to be sure to call you action from route.

I hope that makes sense. You can set it up differently, it is all up to the routing that you create. Let me know if you need help wit route code.

like image 33
bobek Avatar answered Sep 28 '22 05:09

bobek