Reputation: 103
I am using .NET MVC and AngularJS. After making a post request to place an order, I need to return the order that was created to a different view.
I have two views. Purchase Success and Purchase Fail. Here is the post request in Angular:
$http.post('/Home/PlaceOrder/', placeOrderViewModel)
.then(function (response) {
if (response != null) {
window.location = '/Home/PurchaseSuccess';
} else {
window.location = '/Home/PurchaseFail';
}
}, function () {
alert('error');
});
Here is the method on my MVC controller.
public ActionResult PlaceOrder(PlaceOrderViewModel viewModel)
{
}
It accepts a view model from the Angular post request, and does some work. Then I have it returning either the purchase success or purchase fail view with the order model attached to a successful order.
return View("~/Views/Home/PurchaseSuccess.cshtml", order);
return View("~/Views/Home/PurchaseFail.cshtml");
Returning the view does not work. MVC does not seem to be able to handle the change in views since the request was made from Angular? The redirect in the Angular success handler is already working, and works great when you do not have a model being returned.
I basically just need to be able to redirect to the purchase success view with the model.
Thank you for your time!
EDIT: Here is the purchase success and purchase fail controller methods:
public ActionResult PurchaseSuccess()
{
return View();
}
public ActionResult PurchaseFail()
{
return View();
}
Upvotes: 0
Views: 763
Reputation: 1256
When you use Angular to make a request, you are making an Ajax request where the intention is to get some data from server side without leaving the current page.
If you do want to go to another page, it's probably better just use a normal form with a submit button and an action attribute pointing to the page you want to redirect to. Like:
<form action="newPageUrl" method="post">
... // more inputs that carry the data you want to send to server side
<input type="submit">
</form>
However, when people use Angular, it is more often that they just let Angular do the routing/rendering. That means you put your PurchaseSuccess.cshtml
and PurchaseFail.cshtml
on the client side as view templates and let client side render it: You make a post request to submit the order, server receives the order and returns a new data model, client side gets the data model and reders it into the view that it already holds in memory (or request the template file on the fly if you choose to configure it that way).
Upvotes: 1