1

I am using C# ASP.NET MVC and wish to know is there any way to redirect to other page from controller in success condition. For failure condition, it should return JSon result redirect to AJAX method. For this, ActionResult return type is okay for me.

C# Controller:

[HttpPost]
public ActionResult DoMyAction(string var1, string var2)
{
    // Do some action
    if(success)
        Redirect to a page.
    else
        return Json(new { Message = "Action cannot be process..", Status = false});
}

AJAX method:

$.ajax({
        url: '/Home/DoMyAction',
        type: 'POST',
        data: { "var1": "Hello", "var2":"World!"},
        datatype: "json",
        contenttype: "application/json; charset=utf-8",
        success: function (result) {
            if (!result.Status)
                // Display error message.
        },
        error: function () {
        }
    });

Note: Please do not consider syntax here, I wish to know only the way to redirect from C# controller class.

Thanks in advance!

3
  • 1
    You can refer this link stackoverflow.com/questions/17748283/… Commented Jun 24, 2018 at 1:50
  • Ajax calls cannot redirect. You need to redirect in the success callback. But you would be better off doing a normal submit Commented Jun 24, 2018 at 11:27
  • Thanks Stephen and gokul ! This means if we are using AJAX, only option is redirect it from AJAX callback option. Commented Jun 24, 2018 at 14:49

1 Answer 1

2

If you want to redirect to a page using js you can use

window.location.href = 'your url here'

Hope that help. You Need to add this in your success callback or else a normal form submit can be used

Sign up to request clarification or add additional context in comments.

2 Comments

Well this is handled from JS side. I was searching a way to redirect to other page from controller in success condition. For failure condition, it should return JSon result redirect to AJAX method.
You can use RedirectToAction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.