Guide to redirecting using a model following a post request in Angular and .NET MVC

Currently, I am working with .NET MVC in conjunction with AngularJS. My objective is to return the newly created order after initiating a post request to place an order, to a separate view.

The scenario involves two views: Purchase Success and Purchase Fail. Below is the Angular post request code snippet:

$http.post('/Home/PlaceOrder/', placeOrderViewModel)
                .then(function (response) {
                    if (response != null) {
                        window.location = '/Home/PurchaseSuccess';
                    } else {
                        window.location = '/Home/PurchaseFail';
                    }
                }, function () {
                    alert('error');
                });

Furthermore, here is the method within my MVC controller:

public ActionResult PlaceOrder(PlaceOrderViewModel viewModel)
{

}

This method takes in a view model from the Angular post request, performs certain operations, and then ideally should return either the purchase success or purchase fail view along with the order model for a successful order creation.

return View("~/Views/Home/PurchaseSuccess.cshtml", order);

return View("~/Views/Home/PurchaseFail.cshtml");

However, the process of returning the view does not seem to be functioning correctly. It appears that MVC is unable to handle the transition between views when the initial request was made via Angular. The redirect implemented in the Angular success handler works smoothly without any model data being passed along.

In essence, I simply need to successfully redirect to the purchase success view while also passing the necessary model information.

Thank you for taking the time to address this!

EDIT: Additionally, below are the controller methods for both purchase success and purchase fail scenarios:

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

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

Answer №1

Using Angular for requests involves making Ajax requests to retrieve data from the server without navigating away from the current page.

If you need to navigate to a different page, it's advisable to use a standard form with a submit button and an action attribute pointing to the desired page:

<form action="newPageUrl" method="post"> 
    ... // additional inputs carrying the necessary data for the server
    <input type="submit">
</form>

However, in Angular development, it's common practice to delegate routing and rendering tasks to Angular itself. This involves storing view templates like PurchaseSuccess.cshtml and PurchaseFail.cshtml on the client side and allowing Angular to handle the rendering process. Upon submitting an order through a post request, the server responds with a new data model which is then rendered by the client side code into the corresponding view template that was either preloaded or dynamically fetched as needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript element styling in a Partial view, experiencing issues with functionality

In the main view, the javascript element is working fine. However, in the partial view it seems to not be functioning even though it is correctly formatted. Any ideas on how to fix this issue? Check out this fiddle for reference: http://jsfiddle.net/bgrin ...

What caused the increase in response time for the web service?

As I analyze a webservice method, I notice an interesting scenario: [WebMethod] public Response Process() { return RunCode(); } The function RunCode() typically takes 6 seconds to execute, but surprisingly, it takes over 20 seconds for the XML respons ...

Is there a way to make an animated gif function in a WPF dictionary without relying on codebehind?

I am facing a challenge with my dictionary that utilizes a DataTemplate from another class. The dictionary is solely XAML and does not have any code behind. Currently, I am trying to incorporate a live animated gif into this dictionary, but have been unsu ...

Converting an HTML ul-li structure into a JavaScript object: Steps to save the structure

My HTML structure uses ul and li elements as shown below: <ul class="treeview" id="productTree"> <li class="collapsable lastCollapsable"> <div class="hitarea collapsable-hitarea lastCollapsable-hitarea"></div> <span ...

Including a personalized User-Agent string in my headers for fetch requests

Currently, I am utilizing the fetch API within my React project to retrieve data from a JSON endpoint. One requirement I have is to include a custom User-Agent string in my requests. Upon inspecting my requests, I noticed that the UA string displays as: ...

example of using relative jquery countdown.js

I've been attempting to grasp JavaScript and incorporate the countdown found at this link (specifically, the example with a 300-second countdown), but after spending a few hours on it, I haven't been able to get it functioning properly. I have c ...

Handling AJAX requests in ASP.NET for efficient communication

I'm in the process of setting up ajax communication between a JavaScript frontend and an ASP.NET backend. While researching, I came across this sample code on w3schools: function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatecha ...

Sort through a collection of objects based on their content

I'm having some trouble filtering an array of objects based on its content. Here's the code snippet: https://jsfiddle.net/z7g3unyu/2/ var arr =[ { "uid": "1", "name": "John Doe" }, { "uid": "2", "name": "Kate Roe" } ]; ...

I am having trouble with Angular not redirecting to the correct page and I'm not sure how to troubleshoot this issue

After creating a component named detail that is supposed to be associated with a button, I encountered an issue where it doesn't route me to the desired location. Strangely, no error messages are displayed, leaving me puzzled about how to solve this p ...

The maximum property in a Mongoose schema does not have any impact or

const mongoose = require("mongoose"); const PostSchema = new mongoose.Schema( { user_id: { type: String, required: true, }, content: { type: String, max: 150, required: true, }, }, { timest ...

Combining a variety of animations within a mesh

Can someone help me understand this specific example in Three.js? The link is . I am facing some difficulties with the BlendCharacter.js file. this.load = function ( url, onLoad ) { var scope = this; var loader = new THREE.JSONLoader(); load ...

Trouble with innerHTML in a for loop when using getJSON

My current challenge involves displaying a series of JSON results within a div tag using innerHTML. <script> $(document).ready(function() { var html2 = ''; var thread_id = ''; var created_thread_ids ...

The orbitController in threejs is malfunctioning and failing to properly adjust the camera's LookAt

Currently, I am working on a project using three.js. In this project, I have implemented OrbitControls for my camera. However, there are situations where I need to manually adjust the rotation of the camera. The challenge I am facing is that when I try t ...

Unable to modify the title property of a link

Currently, I am in the process of transforming my website to support multiple languages. To achieve this, I have implemented a function using jQuery that dynamically changes text when a language button is clicked. While this method has been successful for ...

Determine the fill color attribute value of a rectangle using Testcafe paired with typescript

Here is a code snippet I need help with: <colored-item label="Label A" symbol-size-left="9.5" symbol-size-right="12" symbol-right="" symbol-left="<svg viewport="0 0 24 24" xmlns="http://www. ...

Managing numerous requests simultaneously without causing one to delay or block the others

I am facing challenges when it comes to managing multiple client requests. Ideally, each route should be handled asynchronously, but I am struggling to handle one request after another without the previous one interfering with the next one. In the code sni ...

Obtaining the data object from a tag in Internet Explorer 8

When using Chrome, the following line of code provides a useful result: $('[data-buyername]').data() It will retrieve the value associated with the tag data-buyername='somethingArbitrary' However, in IE8, the .data() function does no ...

Error detected (unresolved promise): Invalid JSON format is causing an Unexpected token < at the beginning of data position (Application built with React/Redux)

I'm in the process of setting up user authentication using JWT. I've successfully created an API for this purpose. Now, my goal is to integrate this authentication API with my React/Redux App. When a user signs up, I trigger an action from my S ...

Exploring the dynamic loading of JavaScript functions with Ajax in Dojo while passing arguments

Currently, I am working on implementing a require/load function that handles the retrieval and execution of remote JavaScript code. The function is functioning well, but I have been using a workaround to pass arguments by setting global variables. However, ...

Incorporate classes into multiple titles by utilizing the text within the title

Here is some HTML code: <tr class="more-options"> <td width="190px" valign="top" class="ms-formlabel"> <H3 class="ms-standardheader"> <nobr>Required Hidden 1&l ...