简体   繁体   中英

Razor @Url.Action returns with the optional id parameter to a javascript variable

Is it intended that the @Url.Action method returns the current url if the user is currently within the controller and action that the parameters reference?

I have a simple setup for our controllers.

OrderableTest/Details/Id
ResultableTest/Details/Id

If I call @Url.Action("Details", "Orderable") from the home controller (Home/Index) or from the Resultable/Details I will get the proper URL saved to a javascript variable ("/Orderable/Details") . If, however, I am on a Details page then the id gets included in the url. For example, I am on the page Orderable/Details/12345 and I call @Url.Action("Details", "Orderable") , instead of getting "/Orderable/Details" I get "/Orderable/Details/12345" . Is this the intended functionality?

Routing map is default.

Javascript as requested:

var orderableDetailUrl = '@Url.Action("Details", "Orderable")';
var resultableDetailUrl = '@Url.Action("Details", "Resultable")';
alert(orderableDetailUrl);
alert(resultableDetailUrl);

As mentioned by @JotaBe in the comments above, the UrlHelper uses the context information. Thus an @Url.Action called for the page that you're currently on will also include optional id/parameters.

To get around this, you can pass in a blank optional parameter to the method. For my problem above, it was solved with the following code

var resultableDetailUrl = '@Url.Action("Details", "Resultable", new { id = "" })';
var orderableDetailUrl = '@Url.Action("Details", "Orderable", new { id = "" })';

Which both will properly return /Orderable/Details/ and /Resultable/Details/ regardless of which page the user is currently on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM