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.....


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

Saturday, November 23, 2013

17 Step-By-Step How-to Delete rows from a Grid in AngularJS

         By Carmel Schvartzman

In this tutorial we'll learn how to Delete rows from 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 17 in this walkthrough to design an end-to-end AngularJS client MVC app.

In the MODEL-VIEW-CONTROLLER architecture of AngularJS, a 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.

We'll add deleting functionality to an AngularJS table, resulting in the following Grid:


Let's begin by enhancing our backend REST API controller, adding a method that will react in front of any HTTP "DELETE" request. Go to the MVC NatureController and add the method:

"HttpDelete" just tell that any "DELETE" request must be lead to this method. The response will be JSON format, therefore we use the Json object.

Now use the DbContext to find and remove the post:

As you may recall from previous tutorials, we added a DbContext that creates the model, making each table an DbSet<>:


And each DbSet<> enables a bunch of useful functions such as Create(), Find() or Remove():



We added the DbContext code generator in a previous tutorial.:


 The advantage of generating POCO (Plain Old CLR Objects) classes via T4 templates such as the ADO.Net DBContext code Generator is that they offer extensibility over the entity object definitions, far over standard EDMX data access. Also the DbContext can be used with Database First, Model First and Code First programming development. That's why we can use the Find() and the Remove() methods:


Now that we are done for now with the REST API, let's code the invocation of the DELETE API method from the AngularJS app. Open the Blog.js file and INSIDE the AngularJS controller for the current View, add the Delete function:



(See that later parenthesis , which closes the AngularJS controller: you MUST include the method inside it)
Take a look at the AngularJS Documentation, to see how can be used the $resource Delete() method:


Of course, that DELETE call to the REST API must include the ID of the record to be erased:

Take care to respect the case-sensitive approach and write "ID" exactly as it is required by the API REST method:


The "Id" to be sent to the REST server will come from the "Id" of the current post being clicked:


Therefore, the "blog" object must include an "Id" field. Let's create it on the REST API, inside the "GET"  Blogs() method we built in the NatureController:


And of course, let's add that Id to each record being added to the Grid, in the AngularJS View in the BlogList.htm file:



Now that each item on the grid has its corresponding ID, we need a button to delete the items:



Save the project, and CTL-F5 it to activate the web server. Browse to the Index.htm page:


Click on the " X " delete button, to see that nothing happens. Let's add a breakpoint in the JS code. Open the Developer Tools, go to the "Sources" tab , and open the Blog.js file:


Add a breakpoint inside the Delete() function. Press again the delete button:


Well, that's not the problem: the Id has been provided. Remove the breakpoint. Why the item has not been deleted? Let's debug the API. This time press F5 and add a breakpoint inside the Delete() method:



Click again some " X " link. The MVC breakpoint has not been reached. Let's check the request sent. Go to the "Network" tab in the Developers Tools. Clear the list:



Click again the button, and check the "network" tab:


The status code is 200 OK. So the request has been sent and a response received.


The problem is in the URL: the request has been sent to the Blogs() method instead of the Delete(). So let's fix it adding a "ActionName" Attribute to the method:


That means, now the http DELETE verb request will be lead to the correct Delete() method, because the name of the Delete() method will be "Blogs".



Rebuild the project ( F6 ) . Refresh the Index.htm page, and click again the delete button:


This time the deletion has worked:





This is the final appeareance of the AngularJS Grid until now:



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


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