Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

C#JavascriptJqueryasp.net Mvc

C# Problem Overview


I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.

function foo(id)
{
    $.post('/Branch/Details/' + id);
}

My controller code is like this:

public ViewResult Details(Guid id)
{
     Branch branch = db.Branches.Single(b => b.Id == id);
     return View(branch);
}

When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.

I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?

C# Solutions


Solution 1 - C#

You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:

$.post('/Branch/Details/' + id, function(result) {
    // Do something with the result like for example inject it into
    // some placeholder and update the DOM.
    // This obviously assumes that your controller action returns
    // a partial view otherwise you will break your markup
});

On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.

So if you only wanted to redirect the browser:

function foo(id) {
    window.location.href = '/Branch/Details/' + id;
}

As a side note: You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:

function foo(id) {
    var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
    window.location.href = url.replace('__id__', id);
}

Solution 2 - C#

This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.

Here is my code in the view

@Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));

Now you can use this in the JavaScript file as:

 var url = $("#RedirectTo").val();
 location.href = url;

It worked like a charm fro me. I hope it helps you too.

Solution 3 - C#

You can use:

window.location.href = '/Branch/Details/' + id;

But your Ajax code is incomplete without success or error functions.

Solution 4 - C#

// in the HTML code I used some razor
@Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));

// now down in the script I do this
<script type="text/javascript">

var url = $("#RedirectTo").val();

$(document).ready(function () {
    $.ajax({
	    dataType: 'json',
	    type: 'POST',
	    url: '/Controller/Action',
	    success: function (result) {
		    if (result.UserFriendlyErrMsg === 'Some Message') {
			    // display a prompt
                alert("Message: " + result.UserFriendlyErrMsg);
                // redirect us to the new page
			    location.href = url;
		    }
		    $('#friendlyMsg').html(result.UserFriendlyErrMsg);
	    }
    });
</script>

Solution 5 - C#

<script type="text/javascript">
    function lnkLogout_Confirm()
    {
        var bResponse = confirm('Are you sure you want to exit?');

        if (bResponse === true) {
            ////console.log("lnkLogout_Confirm clciked.");
            var url = '@Url.Action("Login", "Login")';
            window.location.href = url;
        }
        return bResponse;
    }

</script>

Solution 6 - C#

check the code below this will be helpful for you:

<script type="text/javascript">
  window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser946393View Question on Stackoverflow
Solution 1 - C#Darin DimitrovView Answer on Stackoverflow
Solution 2 - C#MridulView Answer on Stackoverflow
Solution 3 - C#runView Answer on Stackoverflow
Solution 4 - C#Mike BrownView Answer on Stackoverflow
Solution 5 - C#Muhammad MubashirView Answer on Stackoverflow
Solution 6 - C#shahwaiz hasanView Answer on Stackoverflow