当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net - Confused on the behaviour of the RouteLink helper method

问题描述:

I don't understand why link number 2 below doesn't work :

routes.MapRoute(

name: "GreetingDefault",

url: "Greeting/{action}/{id}",

defaults: new { controller = "Greeting", action = "Index", id = UrlParameter.Optional}

)

;

The links :

1 @Html.ActionLink("ActionLink", "Index", "Greeting", new {area = "" }, null)

2 @Html.RouteLink("RouteLink", "GreetingDefault")

3 @Html.RouteLink("Greet-RouteLink-DisplayGreeting", "GreetingDefault",

new { action = "DisplayGreeting", parameter="abc" })

After clicking on the 3rd link, this is the HTML :

<a href="/Greeting">ActionLink</a>

<a href="/Greeting/DisplayGreeting">RouteLink</a>

<a href="/Greeting/DisplayGreeting?parameter=abc">Greet-RouteLink-DisplayGreeting</a>

then when I click on link 2, it stays at link 3 page, . . instead of going

to "Index" as specified in the named route. I have to do this to make it work :

2 @Html.RouteLink("RouteLink", "GreetingDefault",

new { action = "Index"} )

What am I not seeing here? thanks

网友答案:

The reason for this is that RouteLink picks up current action and uses it in the resulting URL. In your case you are on the page 3, which means your current URL is /Greeting/DisplayGreeting?parameter=abc, and so current action is DisplayGreeting. That is the one RouteLink uses. If you were on the page, say /Greeting/AnyOtherAction, RouteLink would use AnyOtherAction for an action.

Bottom line - RouteLink does not use default action defined for a route when current action canbe used. So basically what you have done with explicit override of the action is a right way to go.

分享给朋友:
您可能感兴趣的文章:
随机阅读: