Paul Zhou
Paul Zhou

Reputation: 193

Url.RouteUrl in js

I have a situation that I need to jump urls in javascript of a ASP.NET MVC site.

As we know, we can generate url with @Url.RouteUrl("RouteName", new { params}) in xx.cshtml. Now I want to generate url in the same way in javascript, is it possible?

I have tried:

window.location.href ='@Url.RouteUrl("RouteName", new {param1="' + param+ '"}) %>'.

However, it doesn't work.

My Route:

routes.MapRoute(
            "ListOfTicketAB",
            "piao/{citystart}-{cityend}",
            new { controller = "Tickets", action = "ListS2S", traintype = 0, sorttype = 0, page = 1 },
            new { citystart = "[a-zA-Z0-9]+", cityend = "[a-zA-Z0-9]+" });

My js:

var selectS;var selectE;function SearchClick(obj) {

        location.href = '@Url.RouteUrl("ListOfTicketAB",new {citystart="' + selectS+ '",cityend="' + selectE+ '"})';

}

selectS and selectE will be set in some other functions.

With Above, I got error:

Server Error in '/' Application.

Illegal characters in path. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Illegal characters in path.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Upvotes: 2

Views: 4149

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

Now I want to generate url in the same way in javascript, is it possible?

No, javascript files cannot execute server side Razor language.

What you could do is generate this url as a global javascript variable in your view or as HTML5 data-* attribute to some existing DOM element that you could access later in your javascript file:

<script type="text/javascript">
    var myUrl = '@Url.RouteUrl("ListOfTicketAB", new { citystart = "_start_", cityend = "_end_" })';
</script>

and then in your javascript replace the 2 placeholders with the corresponding values of your existing javascript variables selectS and selectE:

var selectS;
var selectE;

function SearchClick(obj) {
    var url = myUrl.replace('_start_', selectS).replace('_end_', selectE);
    window.location.href = url;
}

Upvotes: 1

Related Questions