-1

I have one controller HomeController.cs.

In this controller I have some actions like about,contact etc.

If I want that will work I have to defined function to each view:

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

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

I want that for all the requests to the controller it will be return the View(), so I will not have to defined a function to each view.

*Update I want to know if there is some handler that will work something like this:

protected override void OnActionCall()
    {
        return View();
    }
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135

1 Answers1

3

WARNING: I would strongly advise against this as it pretty much defeats the purpose of using MVC but...

You could create a general action that will find the view for you:

public ViewResult Page(string urlSlug)
{
    if (!this.ViewExists(urlSlug))
    {
        throw new HttpException(404, "Page not found");
    }

    return this.View(urlSlug);
}

private bool ViewExists(string name)
{
    ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
    return (result.View != null);
}

You will need to edit your RouteConfig though:

routes.MapRoute(
            name: "Home_Page",
            url: "{urlSlug}",
            defaults: new { controller = "Home", action = "Page" },
            constraints: new { urlSlug = @"[A-Za-z0-9-]{1,50}" }
        );

Now if you look for /about it will look for that view. You will run into problems when you want to use Model data though. I think the time spent asking this question and implementing this solution would take a lot longer than simply having return View()

ediblecode
  • 11,701
  • 19
  • 68
  • 116
  • 1
    while this surely works, this is the kind of thing that goes against MVC conventions, and will be very hard to troubleshoot and maintain. – Claies Mar 11 '15 at 10:42
  • @Claies I wholeheartedly agree - I will put a warning at the top of my answer. – ediblecode Mar 11 '15 at 10:43
  • Honestly, I do not like that people use this argument. This is true, but sometimes this kind of solutions actually prevent problems. I think that the idea of the code is to find common ground, and this solution really find common ground. I would prefer to have a built-in .NET solution of course. – Mosh Feu Mar 11 '15 at 10:46
  • @mosh If you want a bunch of static pages...why not use static pages? – ediblecode Mar 11 '15 at 10:49
  • @jumpingcode I want to use other aspects of MVC like templates routs and other staff. – Mosh Feu Mar 11 '15 at 10:52