开发者

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 mak开发者_如何学Ce me any wiser.


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.


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.


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 = "")
{

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜