Yogendra Paudyal
Yogendra Paudyal

Reputation: 1387

ajax post call to MVC action when i use [Authorize] gives status:200 error

This ajax posts works fine when user is authenticated, but for uanauthenticated user I want to use [Authorize] for redirecting to login.Javascript code look like below...

 $("#favorite").click(function () {
     var favoriteText = $("#favorite").text();
     var status = 1;
     if (favoriteText == "Remove From Favorite") {
         status = 0;
     } else {
         status = 1;
     }
     $.ajax({
         url: '@Url.Action("AddFavorite", "MovieProfile")',
         data: {
             Status: status
         },
         dataType: 'json',
         type: "POST",
         success: function (data) {
             alert('sucsess');
             if (status == 1) {
                 $("#favorite").text("Remove From Favorite");
             } else {
                 $("#favorite").text("Add To Favorite");
             }
         },
         error: function (XMLHttpRequest, textStatus, errorThrown) {
             alert('readyState:' + XMLHttpRequest.readyState + ' status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText, +errorThrown);
         }
     });

 });

And Action is..

[HttpPost]
[Authorize]
public ActionResult AddFavorite(int Status)
{
 //code goes here
}

But it gives error with readyState:4 status:200, status text: OK.

Upvotes: 0

Views: 569

Answers (1)

Kenneth
Kenneth

Reputation: 28737

Since this is an Ajax-call, you cannot redirect from the server. You can only redirect if it's a direct request.

If you do want to redirect on the client-side, you could do this in the error-handler:

error: function (XMLHttpRequest, textStatus, errorThrown) {
     window.location = "/Login";
     alert('readyState:' + XMLHttpRequest.readyState + ' status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText, +errorThrown);
                }

Upvotes: 1

Related Questions