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 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s