PhilippeC
PhilippeC

Reputation: 557

ASP.NET MVC - Failed to navigate in a javascript handler

I am new to Javascript, hope my question is not too obvious.

I have a button in my view: (ASP.NET MVC 4)

<input name="button" type="button" id="button1" value="Click me1"/>

I add a click Handler :

<script>
(function ($) {
    map = new Object();
    map['T1'] = 'Placeholder/Index';
... // Truncated 
    map['T11'] = 'Placeholder/Index';

    $('#button1').click(function ()
    {
        // alert('button1 clicked');
        window.location.href = map['T1'];
    });
})(jQuery)
</script>  

The code works fine the first time I click the button. But, the next times I get an error. I can see in the address bar the following URL:

http://localhost:64321/Placeholder/Placeholder/Index

Why the repetition? What am I doing wrong?
(I have to use Javascript )

(Not the real code, but simplified as much as possible to show the issue)

Thanks in advance
Philippe

Upvotes: 0

Views: 340

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039558

Why the repetition? What am I doing wrong?

Because you forgot a / when you declared your urls:

map['T1'] = '/Placeholder/Index';
...
map['T11'] = '/Placeholder/Index';

or to be more precise you forgot to use the Url helper to generate those urls which is obviously the only correct way to handle urls in an ASP.NET MVC application:

map['T1'] = '@Url.Action("Index", "Placeholder")';
...
map['T11'] = '@Url.Action("Index", "Placeholder")';

Upvotes: 1

Related Questions