Google+

Wednesday, December 18, 2013

18 Step-By-Step How-to Add new rows to a Grid in AngularJS

      By Carmel Schvartzman

In this tutorial we'll learn how to Add new records to a Grid in AngularJS in our AngularJS Blogs Application. Each one of the CRUD (Create - Retrieve - Update - Delete) operations will be covered in successive walkthroughs.You can follow this step by step tutorial as a standalone, or you can learn all the posts to build the entire app. This is the STEP 18 in this walkthrough to design an end-to-end AngularJS client MVC app.

In an RESTful API the corresponding CRUD operations are done according to the HTTP request verb: the GET verb is for RETRIEVE, the POST verb is for CREATE, PUT verb  is for UPDATE and the DELETE verb for deleting of course. In previous tutorials we already used the GET and DELETE http verbs, in order to retrieve and delete data from the REST API back end. In this walkthrough we'll send requests using the POST http verb.



We'll create the Add functionality on an AngularJS table, resulting in the following Grid:



First, we'll create the REST API backend functionality, meaning the ASP.NET MVC controller method which handles the http POST requests. So go to the NatureController where our API is, and add the following method:


The method just returns a JSON object that represents the ERROR case.
Take a look at the AngularJS documentation in the AngularJS.org site: there under the $resource directive you'll find the different http verbs and its corresponding functions: we'll just use the save() function which sends POST requests to the server:



Now code an "if" to check for invalid or null input:


In case is valid, we add the post to the Blogs table, and save the context:

Remember that the Blogs entity inherits from DbSet<>, and therefore we can use its very useful methods like Remove(), Add(), Create(), find() and so on:


Remember we are using an Database First Entity Model, but we added a DbContext Code Generator :


That template created the POCO (Plain Old Clr Objects) Classes for us:


For example, this is the Blogs class automatically generated by the DbContext:


We have just upgraded our REST API made up using an MVC Controller. Now we'll go to the markup and add a button to the Grid, to create New items. Go to the BlogList.html file:


Append to the Table headers a button to go to the " #/New "  page:  in AngularJS, being a Simple Page Application, there is only one page: in a while we'll map that url to a file called "TemplateUrl" file:



Save and refresh, and take a look at the app:


Next, we'll map that address to an AngularJS Controller and a Template: find the $routeProvider in the Module at Blogs.js:


Add the following mapping, meaning that the html template in file "Details.html" must be linked to the NewCtl Controller. In the MODEL-VIEW-CONTROLLER architecture of AngularJS, a Template VIEW is related to a MODEL in the configuration step of the AngularJS app live, when we link it to some CONTROLLER.
This linking action is set in a Module, with the function of declaratively set how the AngularJS app should be bootstrapped. It's like the Main method in a program, setting the instantiation of the application.
Because AngularJS is based on the Dependency Injection paradigm, here is the place to configure the app injecting the functionality that we'll need.


Next, let's create that Controller: it will get as parameters the $scope(to get and set the scope variables), a $location (to allow us to redirect the user), and the $resource BlogResource:


As you recall from previous tutorials, the $resource was created in the Factory of our app, and it worries for the sending of requests to the web server:


Inside the Controller, we define a new function to send POST requests to the web server:

That function uses the save() function of the  $resource, sending an "$scope.blog" object to the server, named "post"(as it was named as a parameter to the Create( Blog post) MVC method in the backend):


We just use the save() function of the $resource, as explained in the AngularJS documentation:


That function defines a callback in case of success: inside we just redirect the user to the main Blogs List to see the posts, using the $location directive:



Now we create the Details.html , the html which will be the Create Form template:


Add a new html file(take care of adding it in the same folder of Index.htm and BlogList.html):


There type an H1 as a title, using the "Action" variable:


Create that variable in the Controller:


Next, add two buttons: one for Canceling and the other for Saving the posts: the Cancel just redirects the user to the main View, and the Create just calls the Create() function:


 Now because the Blog includes some properties, we'll add them to the form to edit them:


For the first property , add a div with a label and an input:


We bind the input control to the "Title" field of an "blog" object which the AngularJS engine will create for us. You can name it whatever you want, provided that the save() function sends it to the web server.

Save and refresh to see the form:


Now do the same thing for the rest of the fields to bind:


Save and refresh:


Now try to save the New post:


Nothing happens. Open the Develope r resources (F12) and go to the "Network" tab, to see the request sent. The status is 200 (OK):


Take a look at the request's Headers: the "post" object contains the data , but you can see the request's URL is targeting the "Blogs()" method:


The response received is produced by that Blogs method, not by the Create() method as we wanted:


Let's add the ActionName "Blogs" so that the request is properly handled:




Set a breakpoint inside the method to catch the request. Press the button again and see the "post" object:


It's OK, and now the response is what it shoud be:




And certainly, the post has been saved:



Finally, add styles to the Template, using the Twitter Bootstrap, and also add the ng-class directive that follows, that will  be set in case of illegal input:



Do the same for the rest of the properties:



Also add style to the buttons:



Save- Refresh to see the Simple Page Application in action. Instead of a date, input some text:



You'll see that the state is now invalid, so the post will not be saved:



Type a legal date:


This time the post has been saved:



That's all!! 
Happy programming.....


כתב: כרמל שוורצמן