How do I set a “Default Action” for my Controller that will be called when no other action matches?

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).


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.

Need Your Help

x axis domain issue in D3 Line chart

charts d3.js line

I have drawn a Line chart in D3. I am facing issue in x axis alignment.Fiddle Link