Ali
Ali

Reputation: 57

ASP.NET Core MVC Post Request from JQuery but need to redirect from Controller Action

I have ASP.NET Core 2 MVC project. I am posting some data using JQuery to action. Suppose User.Identity.Name is null and I want to redirect to AccountController AccessDenied action. I am unable to use RedirectToAction (also removed return). Because this goes back to JQuery success/error.

Is there any solution to this?

IN Controller

if (string.IsNullOrEmpty(User.Identity.Name))
    return RedirectToAction(nameof(AccountController.AccessDenied), "Account");

In My JS

$.ajax({
        type: "POST",
        url: '/MyController/MyAction',
        dataType: "json",
        data: $(this).serialize(),
        success: function (data, status, xhr) {

        },
        error: function (xhr, status, err) {
            errorAlert(xhr.responseText, "ERROR");
        }
    });

Upvotes: 1

Views: 1948

Answers (2)

Daniel Manta
Daniel Manta

Reputation: 6683

Let Ajax error function to redirect when server response is access denied.

error: function (xhr, status, err) {
    if(xhr.status==401) {
        window.location.replace('@Url.Action("AccessDenied", "Account")');
    } else {
        errorAlert(xhr.responseText, "ERROR");
    };
}

From controller return http error 401, so that it will trigger error Ajax function at client.

return Unauthorized();

Upvotes: 1

RAHUL S R
RAHUL S R

Reputation: 1579

so here is the deal when you do an ajax call it expects a return value and hence you cannot redirect an ajax call from the server side but you can do one thing u can send the url as string to which you want to redirect and then redirect it from client side ie

if (string.IsNullOrEmpty(User.Identity.Name))
    return "YourController/YourAction/ParamifAny";

and in controller side

$.ajax({
        type: "POST",
        url: '/MyController/MyAction',
        dataType: "json",
        data: $(this).serialize(),
        success: function (data, status, xhr) {
         window.location.href = data
        },
        error: function (xhr, status, err) {
            errorAlert(xhr.responseText, "ERROR");
        }
    });

Upvotes: 1

Related Questions