tags:

views:

396

answers:

1

Say I have the following route:

routes.MapRoute("Default", "{controller}/{action}/{id}", 
    new { controller = "Home", action = "Index", id = "" });

Lets also say that my controller has the following methods: Index(Int32 id) and Edit(Int32 id).

So /MyController/Index/1 is a valid URL for that route. So is /MyController/Edit/1

However, if a URL is received that correctly maps to my controller but not to an existing action, how do I define a "Default Action" to execute instead of letting the MVC framework throw up an error screen?

Basically I'd like the URLs /MyController/Preview/1 and /MyController/Whatever/1 to execute an action that I specify ahead of time when the {action} token can't be mapped to an existing action on my controller.

I see that the MvcContrib project on Codeplex has an attribute that enables this for use with the ConventionController, but I'd like to keep this with pure MS ASP.NET MVC for now.

I also see that Fredrik mentions a [ControllerAction(DefaultAction = true)] attribute, but I can't find mention of it anywhere except his blog (and my app won't compile when I try it in my controller).

+3  A: 

You can do the following for now.

protected override void HandleUnknownAction(string actionName) {
  //your code here.
}

Another approach is that you put a constraint on the default route so it only matches methods you know exist on the controller. Then you could have another route like so:

routes.MapRoute("default-action", "{controller}/{actionName}/{id}", new {action="DefaultAction"});

Which maps to

public ActionResult DefaultAction(string actionName, string id) {
  //handle default action
}

This gets you the result you're looking for.

Haacked
This works, but after messing about with it for awhile I decided that I like the simplicity in simply applying an attribute to an existing action.I'm already using something like the "OpinionatedController" so it wasn't much effort to add that in with inspiration from the MVCContrib stuff.
Hellfire