Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 How to use MapRoute

Could someone show me how to use the MapRoute method? I have tried creating my own routes, but it's not working. What i want to accomplish is a route that routes "http://servername/home/default.aspx" into controller "Home" and action "Default". Also, would it be possible to say that if the user is browsing the default.aspx "file", it would actually point to the "Index" action?

I have tried reading the MSDN references and googling, but it didn't make me any wiser.

like image 654
Anton Gildebrand Avatar asked Jun 22 '11 12:06

Anton Gildebrand


3 Answers

Probably too late to help the developer who raised the question but may help someone else. New to MVC but what I found is the map routes seem to be processed in the order they are added. I had a similar problem, my specific route was not working until I started adding the default route as the last route.

If the default map route is added before your custom one and your custom URL matches the structure defined by the default map route you will never reach your custom route.

like image 154
Darren Hughes Avatar answered Sep 22 '22 13:09

Darren Hughes


The route you want to configure the first part of your question is:

routes.MapRoute(
    "",
    "home/default.aspx",
     new { controller = "Home", action = "Default" }
);

Assuming you wish to 'browse' default.aspx with some sort of parameter you can do something like:

routes.MapRoute(
    "",
    "home/default.aspx/{param}",
    new { controller = "Home", action = "Default", param = UrlParameter.Optional }
);

And you would then need to create your Default action to accept string param.

like image 40
Antonio Haley Avatar answered Sep 25 '22 13:09

Antonio Haley


You also have to make sure the parameter name is the same as the action's parameter name. Example:

    routes.MapRoute(
        name: "MyName",
        url: "{controller}/{action}/{myParam}",
        defaults: new { controller = "MyController", action = "MyAction", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

MyController:

public ActionResult MyAction(string myParam = "")
{

}
like image 37
live-love Avatar answered Sep 23 '22 13:09

live-love