0

I am trying to redict to another MVC View from a an Angular 1.6 $http.post. Basically I want to go to another View (Checkout) to display the options user has selected from Details page. The trouble I am having is that if I go directly to Checkout I get a NullReferenceException, so I tried this:

Angular:

model.submitDetails = function () {

        // Commented out code results in NullReferenceExeption - not binding the data

        //var data = {
        //    car: model.car, colour: model.colour, features: model.features, cover: model.cover
        //}

        //window.location = 'http://localhost:50592/Cars/Checkout?vm=' + data;


        $http.post('http://localhost:50592/Cars/DetailsSubmit',
                { car: model.car, colour: model.colour, features: model.features, cover: model.cover })
            .then(function (response) {
                window.location.href = response;
            }, function (err) {
                model.error = err.data;
                console.log(err.data);
        });
    };

The above $http.post results in a 404 error. If I don't include the .then, e.g. comment it out, I can see in the Network tab in F12 dev tools that the $http.post is returning the html directly rather than rendering the Checkout View page.

My MVC Controller Code:

[HttpPost]
public ActionResult DetailsSubmit(CheckoutViewModel vm)
{
    TempData["car"] = vm.Car;

    vm.StartDate = DateTime.Now;
    vm.EndDate = DateTime.Now.AddDays(7);

    return RedirectToAction("Checkout", vm);
}

public ActionResult Checkout(CheckoutViewModel vm)
{
    vm.Car = (Car)TempData["car"];

    return View(vm);
}

To how can I redirect successfully to the Checkout page from the submitDetails() Angular function? Any help getting this working would be greatly appreciated.

2 Answers 2

2

It looks like you're trying to redirect with a payload. That's not possible. A redirect actually introduces a totally separate request. The server returns a response with a status code of 302 (typically) and a Location header that indicates where the client can find the document that has "moved". The request-response cycle is totally complete at this point. The client, then, will generally go ahead and request that new URL, but that is 100% on the client, and importantly, the client will not pass any data not present in the URL with this GET request.

If you need to persist information between requests, then you must either store it in a database or use something like Session or TempData. You are then responsible for "restoring" this data on the next request the client makes.

That said, there is absolutely zero point in doing an AJAX post if all you intend to do is redirect. The whole point of AJAX is to stay on the page, whereas a redirect causes a new page to be loaded. Just do a normal post, and you can actually just return your view (along with the posted data) from that post action. No need to store anything. However, if you need to make further request, you'll have to continue passing this same post data (plus any additional) along each time, or again, persist it somewhere like the database or session.

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

1 Comment

Ok, yes makes sense - thanks for this answer Chris, means I can stop going around in circles with this approach.
2

Your MVC controller doesn't look correct, you can introduce a: return Redirect(URL); within your post DetailsSubmit method.

Your Angular http call should JSON.stringify() the data you are sending across the wire, for example:

model.submitDetails = function () {

    var data = JSON.stringify({car: model.car, colour: model.colour, features: model.features, cover: model.cover});

    $http
        .post('/Cars/DetailsSubmit', data, {headers: {'Content-Type': 'application/json'}})
      .then(function (response) {
            // do somethings i.e. display a success message
            // then
            window.location.href = response.body.url;
            return;
        }, function (err) {
            model.error = err.data;
            return;
        });
};

4 Comments

Getting - Cannot read property 'url' of undefined error on F12 console - the response is the actual html, I can see the page that should be redered in the preview. If I try just response.body - get the 404 error.
The response was just an example. If you console log the response you should be able to view the object and find the property for the URL you're wanting to attain!
If I try and redirect that way then I just get the NullReferenceException as the MVC View has no knowledge of the model.

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.