0

I have a dropdown that allows users to select a data feed to view. The first time a user selects one, my URL looks like this:

http://localhost/DataFeeds/Viewer/1

On the second selection, it looks like this:

http://localhost/DataFeeds/Viewer/1/2

That's obviously not correct. The 1 should be replaced with the 2.

Here's the code that causes it:

$('select#ID').change(function () {                
    window.location.replace("@Url.Action("Viewer", "DataFeeds")/" + $(this).val());
});

I've already tried

window.location.href = "@Url.Action("Viewer", "DataFeeds")/" + $(this).val();

but that does the same thing.

All suggestions appreciated.

keeehlan
  • 7,874
  • 16
  • 56
  • 104
  • It looks like you're concatenating the two strings rather than replacing the 1. try replacing the one using RegExp or similar. – BenJamin Jul 09 '13 at 22:35
  • In your example ```window.location.href = url``` what is the value of url? Can you put some debugger statements in to see what is happening at that point? – Wheeyls Jul 09 '13 at 23:19

2 Answers2

1

Following response is wrong. window.location.replace() does redirect, my bad !

Actually window.location.replace() is the same as window.location = url, with the small difference that replace() removes the old location from the browser history, and thus not making it possible to use the back button.


Bad response:

You are replacing not assigning

window.location = window.location.replace("@Url.Action("Viewer", "DataFeeds")/" + $(this).val());


// This does not redirect it just grabs the string of the location and modifies it
window.location.replace("@Url.Action("Viewer", "DataFeeds")/" + $(this).val());

// is the same as doing
var redirectTo = window.location.replace("@Url.Action("Viewer", "DataFeeds")/" + $(this).val());

// you still need to do
window.location = redirectTo;

However

If it doens't work like you said, then replace("@Url.Action("Viewer", "DataFeeds")/" + $(this).val()); is flawed.

Robert Hoffmann
  • 2,366
  • 19
  • 29
0

There is another answer on stack overflow which answers this question. I was having the same issue and found that I needed to use the ?name= syntax mentioned here: Passing dynamic javascript values using Url.action()

instead of using this:

$('select#ID').change(function () {                
    window.location.replace("@Url.Action("Viewer", "DataFeeds")/" + $(this).val());
});

try using something like this:

$('select#ID').change(function () {                
    window.location.replace("@Url.Action("Viewer", "DataFeeds")?id=" + $(this).val());
});

When using the ?name= syntax, the ending no longer concatenated for me.

Joel Youngberg
  • 444
  • 1
  • 8
  • 7