Navin Pandit
Navin Pandit

Reputation: 179

Redirect to a page using C# controller while using AJAX method in ASP.NET MVC

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!

Upvotes: 1

Views: 178

Answers (1)

user4851087
user4851087

Reputation:

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

Upvotes: 2

Related Questions