Posts Tagged WebAPI

Insert functionality in UIGrid

Introduction

This is a continuation of my previous articles in which I demonstrated the procedure to

In this article I will demonstrate how to implement Add new record functionality in Angular UIGrid.

Prerequisites:

I have used icons from FontAwesome Library, which is a great source for multiple icons. You can download Fontawesome icons from here.

To display message after every operation we used UIBootstrap.

Implementation:

You would already have the Model configured by following my previous article on loading UIGrid with data. We will directly look into the details of Adding new record in UIGrid.

You can see a sample Demo of entire functionality below.

demo

UIGrid Updates

We will add a new button on page which responds to click event and open a modal pop up window. Users can enter the details and on save button click we will save the data to database.

AddCustomer function:

AddCustomer function will take the scope object as input which contains all values as provided by user and then save the data to database. User will also see an alert stating the status of insert operation.

Updated Angular code with Insert new Record functionality

Modal Pop up HTML

WEBAPI AddCustomer Method

You can find complete source code of this demo from github

Advertisements

, , , , , , ,

Leave a comment

Implementing delete functionality in UIGrid

Introduction

This is continuation to my previous two articles in which I demonstrated the steps to

In this article I am going to demonstrate how to implement row delete functionality in UIGrid.  The series will contain continuation articles to cover the topic in detail.

Prerequisites:

I have used icons from FontAwesome Library, which is a great source for  icons. You can download Fontawesome icons from here.

Also to display message after every operation we used UIBootstrap

Implementation:

You would already have the Model configured by following my previous article on loading UIGrid with data. We will directly look into the details of deleting records in UIGrid.

Sample Demo of Delete functionality is given below

Demo

UIGrid Updates:

We will update cellTemplate in “Actions” column to add Delete button. We will reuse the editRow flag to hide and display delete buttons.  To delete the record,, we call deleteRow function from Delete button

Delete function:

Delete function will take the selected row object as input parameter; we will find the rowindex using input parameter. Using row index we will find CustomerID of selected row and delete the record. Additionally before deleting the record we will ask for user confirmation. Finally we will call the DeleteCustomer method in Factory service to delete the record in database.

Updated Angular code with Delete functionality

HTML

Delete Customer Method(WEBAPI)

 

, , , ,

1 Comment

How to implement row edit functionality in Angular UIGrid

Introduction

In this article I will explain the procedures to implement row level editing functionality in Angular UIGrid. This is a continuation of my previous article in which I showed the procedures to populate a UIGrid.

Prerequisites:

I have used icons from FontAwesome Library, which is a great source for  icons. You can download Fontawesome icons from here.

Also to display message after every operation we used UIBootstrap

Implementation:

You would already have the Model configured by following my previous article on loading UIGrid with data. We will directly look into the details of Editing in UIGrid.

UIGrid by design supports the inline edit functionality by double clicking on a particular cell. In this article we will implement editing all columns in a row using button click and save the details to database on Save Button click.

You can see a sample demo of editing functionality below

Demo

UIGrid Updates

We will use the cellTempalate, to make the cell editable. We are using a flag to make the row editable. When user click on the Edit button, we will set the EditRow flag as true. Later in the UIGrid, we check if the flag has been set to true or false. Based on the flag value the row will be editable or readonly.

We will update cellTemplate in “Actions” column to add Edit, Update, Cancel button. We will reuse the editRow flag to hide and display Edit and update buttons.  Also we call edit, saveRow, CancelEdit functions from Edit, Update and Cancel buttons respectively.

Edit function:

Edit function will take the selected row object as input parameter, we will find the rowindex using input parameter and set the editRow flag for selected row to true. This will make the UIGrid row editable.

cancelEdit function:

cancelEdit function will take the selected row object as input parameter, we will find the rowindex using input parameter and set the editRow flag for selected row to false. This will make the UIGrid row read only.

saveRow function:

saveRow function will take the selected row object as input parameter, we will find the rowindex using input parameter and set the editRow flag for selected row to false. This will make the UIGrid row read only.  Next line of code will read the values from edited row and assign it to customer class in scope. Finally we will call the SaveCustomer method in Factory service to update the record in database.

Updated Angular JS Script:

HTML

UpdateCustomer Method(WebAPI)

 

, , , , , ,

1 Comment

How to populate Angular UIGrid in MVC using AngularJS

Description

In this article I will explain the steps for populating UI-Grid in angularjs from database using WebAPI. UI-grid is a powerfull tool which provides a table like representation. Apart from table like structure Ui-Grid also provides functionality like filtering, sorting, exporting etc.  You can find more details about UI-Grid from here

PreRequisites:

Ui-Grid is dependant on AngularJS.Hence ensure that you have added reference of Angular js on page.

Implementation:

Model:

To load the data from database, we are using EntityFramework and its related method. In this example I have used the DatabaseFirstApporach.  DatabaseFirstApporach lets the EnityData Model to generate classes, dbcontext etc from the database automatically. All other functionalities like database and model sync exists as is.

Follow the below procedures to generate Model for Customer database in Northwind database

  • Right click on the Model folder
  • Select Add option
  • And then select the New Item option
  • Choose Data from Installed Templates group
  • Select the ADO.NET Entity Data Model option and Provide a name for it
  • In the Entity Data Model Wizard, Select EF Designer from database and click on Next
  • Choose the Connection string options
    • If you already have connection string configured then you can select that from the available list.
    • If you don’t have the connection string configured then use the New Connection option and create the connection
  • Expand the Table option and then select the tables which you want
  • Click on Finish

You will have necessary class files generated in your solution now

Northwind

You can get more details about how to use DatabaseFirst approach from this link.

Controller (WebAPI)

In this example we are using WebAPI to load the data. The next procedure is to write code to fetch records from database using WebAPI.  For this demo I have used a basic select operation. You can modify this as per your need.

Another point to note here is UI-grid read data which is in Json format, Hence we need to ensure that the data which we return from controller is of Json format. We will use the JsonResult method for this.

View:

On View we will have the codes for UI-Grid and its related files. If you look at the design of UI-Grid it’s a div which will be styled to look like a table at runtime.

We need to add div with an attribute as ui-grid=”gridOptions”.  We add all the details from angular js code to gridOptions and UI-Grid at runtime uses this div to populate the grid.

RouteConfig Changes:

I have changed the Action Name from “Get” to “GetCustomer” to be more specific with what the method do. In order for api to identify the proper method add the below route setting to web api route config

Angular JS Script

Below are the code to fetch the data from database and populate it to UI-Grid. I have used a factory to call the Get Customer method and used that in the main method.

 

, , , , ,

1 Comment

How to load data from database to Asp.Net Gridview using WebAPI

Introduction:

In this article we are discussing how to load data from database to Asp.Net Gridview using WebAPI.

Description:

We use WebAPI to get the data from database and then use the Jquery getJSON() method to Load JSON-encoded data from the server using a GET HTTP request.

Implementation:

In the New ASP.NET Project dialog, select the Empty template. Under “Add folders and core references for”, check WebForms , Web API. Click OK.

2016-04-30 19_11_49-Microsoft Visual Studio (Administrator)

When using WEBAPI you will get data in client side and you need to manipulate it at client side so that the data will get populated in Gridivew. Point to note here is we cannot go with the normal approach of setting DataSource and calling DataBind method. We have various options to load data into grid like AngularJs, Jquery etc.

As mentioned earlier in this article I am using getJSON() method to fetch the value and then populate the data in gridview. Gridview will load as table at runtime we will access this table and then append the values to it.

2016-04-30 14_29_24-http___localhost_52678_WebForm1.aspx - Internet Explorer

Sample Code:

HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script type="text/javascript">
        //Code to load the data to gridview on pageload
        $(document).ready(function () {
           //Here you need to provide the webapi address
            $.getJSON('api/Customer')
                .done(function (data) {
                    $.each(data, function (key, item) {
                        //Add the result to gridview
                        $("#GridView1").append("

<tr>

<td>" + item.CustomerID + "</td>


<td>" + item.CompanyName + "</td>


<td>" + item.ContactName + "</td>


<td>" + item.ContactTitle + "</td>


<td>" + item.Address + "</td>

</tr>
");
                    });
                })
            .fail(function (d) {
                alert("error occured" + d.responseText);
            });
        });
    </script>
</head>
<body>
<form id="form1" runat="server">
<div>
            <asp:GridView ID="GridView1" runat="server" Width="1000px" ShowHeaderWhenEmpty="true"                 CellPadding="0" CellSpacing="0">
            </asp:GridView></div>
</form>

</body>
</html>

C#:

First we need to populate an empty row in GridView. Reason behind this is if we didn’t assign any datasource then the GridView won’t populate at runtime and we won’t be able to access it at client side.

protected void Page_Load(object sender, EventArgs e)
        {
            //Load and empty row to gridview
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(&quot;CustomerID&quot;);
                dt.Columns.Add(&quot;CompanyName&quot;);
                dt.Columns.Add(&quot;ContactName&quot;);
                dt.Columns.Add(&quot;ContactTitle&quot;);
                dt.Columns.Add(&quot;Address&quot;);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

WebAPI Code:

When we add the WebAPI references in your project you will see a Model folder and Controller folder.

2016-04-30 19_20_50-WebAPISample - Microsoft Visual Studio (Administrator)

Model

Here we add the Model classes which basically represents data in WebAPI. For this article we add Customer class. Right Click on the Model folder and choose Add and then select class file. Name it like Customer

public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
    }

Controllers:

In controller we will add the code to fetch values from database. Right click on the Controllers folder and Choose Add and then select Controller. In code you can see an HttpGet entry added above to GetCustomers method. This is because Rest WebAPI is making use of verbs(Get,Post,Put,Delete) for each actions in Read,Create,Update,Delete respectively. You can get more details from here

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiSample.Models;

namespace WebApiSample.Controllers
{
    public class CustomerController : ApiController
    {
        [HttpGet]
        public IEnumerable<Customer> GetCustomers()
        {
            Customer[] aryCustomers = null;
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NORTHWINDConnectionString"].ToString()))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "SELECT TOP 10 CustomerID,CompanyName,ContactName,ContactTitle,Address FROM Customers";
                    conn.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        List<Customer> lstcustomers = new List<Customer>();
                        while (reader.Read())
                        {
                            lstcustomers.Add(new Customer
                            {
                                CustomerID = reader["CustomerID"].ToString(),
                                CompanyName = reader["CompanyName"].ToString(),
                                ContactName = reader["ContactName"].ToString(),
                                ContactTitle = reader["ContactTitle"].ToString(),
                                Address = reader["Address"].ToString()
                            });
                            aryCustomers = lstcustomers.ToArray();
                        }
                    }
                }
            }
            return aryCustomers;
        }
    }
}

, , , , , , ,

Leave a comment