MVC Redirect from View with Parameters

I needed to redirect to another view using JavaScript for which I encountered quite some issues to do so.

1. First of all, windows.location.href = “http://….” would not work.

2. Then I discovered that what needed to be done to redirect to another view was:

window.location.href = ‘@(Url.Action(“Index”, “Home”))’;

3. However, I needed to pass a search query and so I added the normal new parameter:

var mySearchQuery = $(“#mySearch”).val();

window.location.href = ‘@(Url.Action(“Index”, “Home”, new { search = mySearchQuery }))’;

The above kept on giving me error, no matter what I tried to put instead of mySearchQuery.

4.Finally, I found the solution for this. Which was:

var mySearchQuery = $(“#mySearch”).val();
var tempUrl = ‘@(Url.Action(“Index”, “Home”, new { search = 0, }))’;
var actualUrl= tempUrl .replace(“0”, mySearchQuery );
window.location.href = actualUrl;

Hope that helped 🙂