In the last Post we have seen that how to post a form basically to an MVC action using Angular. we have also verified data being posted @ the chrome (client) level and at the server level as well. Now, moving ahead, let’s see how to handle the incoming server responses in this case. So, basically we want to handle 2 scenarios where in it successfully post the data and the other one where in it gets failed to post the data. So, let’s 1st see the happy path scenario.
so, here is the same thing which we have seen in the previous case. we have basically added $q library to handle the promises. Here, what am doing is upon successful submission am redirecting user to the movies page as shown below.
However, currently the movie didn’t get added. So, will handle this case later, but good news is that on successful submission we get redirected to Movies page. Now, let’s handle the scenario, where in returned some error while saving the same. So, to quickly test the same instead of returning 200 ok status from the PostMovie Controller let’s return internal server error.
Now, when i build and refresh the same and then try to post the result, nothing will happen because we have not handled the error response scenario in our case yet. But, we can inspect the same in the chrome console as shown below.
No, problem now let’s go ahead and handle the same as well.
so, what will happen here, when user hits Post Movie, if it is successful then in that case it will redirect it to the movies page, now if there is some error while saving the same then it will just the error flag to true, which we will handle in our html to produce the error on the screen.
so, what will happen here, this ng-show will become active when error flag returned true from the controller. so, the above said message will be published on the screen.
now, let’s see that how to achieve the same using web api. so, here what will do MVC will take care of serving the views and web api will take care of serving the endpoints. so, let’s get started changing the same with movies controller as shown below.
so, with web api we don’t care of returning JSON explicitly, it’s the property of web api to return the json of the underlying model by default, so we just need to pass on the method in there and it will take care. so, now i have to modify my movies repository as well, i need to include api in the url. well this is how web api works.
Now, when i build and refresh then i can see that api is working properly. Now, let’s go ahead and make the same changes to reviews part.
Download Link:- MVCPlusAngular
So, with this i would like to wrap this module and in the next section we’ll see more on angular validation and using resources more effectively. Till then, stay tuned and happy Coding.
1,966 total views, 1 views today