2

I am generating an URL in JavaSctipt. The first time I generate this URL I get the correct URL: E.g. **http://localhost:54415/NffCall/Details/DK/6607726**

But the next time I generate the link I get the previous link combined with current parameters: E.g. http://localhost:54415/NffCall/Details/DK/6607726/DK/6608146

The code which genrates my URLs looks like this:

var actionUrlBase = '@Url.Action("Details", "NffCall")';
var actionUrl = actionUrlBase + '/' + countryCode + '/' + orderNumber;
window.location.href = actionUrl;

What shall I do to generate the correct link every time?

EDIT: I will just paste how the RouteCollection looks like:

routes.MapRoute(
    name: "CountryCodeOrderNumberDetails",
        url: "{controller}/{action}/{countryCode}/{orderNumber}",
        defaults: new { controller = "NffCall", action = "Details", countryCode = (string)null, orderNumber = (int?)null },
        constraints: new { countryCode = "[a-zA-Z]{2}", orderNumber = "[0-9]+" }
);

routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Rune Hansen
  • 954
  • 3
  • 16
  • 36

1 Answers1

2

Use the Helper @Url.RouteUrl instead.

var actionUrlBase = '@Url.RouteUrl("Default",new {action="Details", controller= "NffCall"},Request.Url.Scheme)';
var actionUrl = actionUrlBase + '/' + countryCode + '/' + orderNumber;
window.location.href = actionUrl;

This site explains it very well: http://www.patridgedev.com/2011/08/22/subtleties-with-using-url-routeurl-to-get-fully-qualified-urls/

DJ.
  • 528
  • 7
  • 16
  • Hi Djavier, thank you for your reply, but it seems that your code behave exactly the same way as my current code, so the problem persists. – Rune Hansen Nov 06 '13 at 14:48
  • 1
    What if you try by @Url.RouteUrl("Default",new {action="Details", controller= "NffCall"},Request.Url.Scheme), this will definetly get you the Url Scheme for the routing configuration you set. – DJ. Nov 06 '13 at 19:13
  • Hi Djavier, it seems like the last code you provided here in the comment makes my code work. I don't really understand why your last code works, and why my code didn't work before. But it seems to work as it should now. So this might be an answer. – Rune Hansen Nov 06 '13 at 20:19
  • Glad it helps, there a some strange things when working with the routing and rendering urls using the helpers. i've been through this fellow! Please vote up the answer! – DJ. Nov 06 '13 at 20:42
  • Thank you Djavier, I have edited your answer to put the code from the comment there. I hope your code will work out in production on the server as well. Thank you. – Rune Hansen Nov 07 '13 at 08:22