Nitin Kumar Mishra
Nitin Kumar Mishra

Reputation: 315

Redirection in ASP.NET MVC to a controller method after the post AJAX call

Present set up -

url: configMap.sitePath + "api/Quiz/" + quizResponse.quizId,
                    data: JSON.stringify(quizResponse),
                    success: function (data) {
                       // Display the data on UI 
                    }

the above post is to a .NET api controller which returns quizResponse.

    [ValidateModelState, HttpPost]
    public HttpResponseMessage Post(int id, QuizResponse value)

Now as per a new requirement , Once the api has the response I should redirect to another page(a MVC controller and then view). How do I achieve this -

    public ActionResult ScptResult()
    {
        return View();
    }

I also thought of redirect after ajax success but not sure if its a correct way. Also, How do I pass data to the scptresult controller method after post?

Upvotes: 0

Views: 1431

Answers (3)

christo8989
christo8989

Reputation: 6826

I should warn, I'm not very familiar with ajax responses but hopefully this gets close.

API

[ValidateModelState, HttpPost]
public HttpResponseMessage Post(int id, QuizResponse value)
{
    //Other stuff...
    var redirect = string.Format(@"/controller/ScptResult/{0}", id);
    return new HttpResponseMessage()
    {
        Content = new StringContent(redirect)
    };
}

Javascript

url: configMap.sitePath + "api/Quiz/" + quizResponse.quizId,
                data: JSON.stringify(quizResponse),
                success: function (data) {
                   window.location = data; 
                }

Controller

// This follows the default route. 
// "/{controller}/{action}/{id}" where id is optional.
// window.location = "/ControllerName/ScptResult/OtherData"
public ActionResult ScptResult(string id)
{
    return View();
}

Upvotes: 0

Sunil Kumawat
Sunil Kumawat

Reputation: 41

Use in java-script after complete your work in success method or anywhere

window.location = '@Url.Action("ScptResult", "YourControllerName")'; 

Upvotes: 0

Jesse Sierks
Jesse Sierks

Reputation: 2397

In the success function of your JQuery, redirect the page to your MVC page:

window.location = '{controller}/{action}/{quizid}';

Assuming you use the standard MVC routing, and assuming you change your ScptResult function to accept a parameter, so you can pass data to it.

public ActionResult ScptResult(int quizid)
{
    return View();
}

Upvotes: 1

Related Questions