• Introduction

    I will demonstrate how we can create sample CRUD (Create, Read, Update, Delete) operations using ASP.NET, Web API, and Knockout.js. I hope you will like this.

    Prerequisites

    First, you must have Visual Studio 2015 (.NET Framework 4.5.2) and a SQL Server.

    In this post, we are going to:

    1. Create an MVC application.
    2. Configure an Entity framework ORM to connect to a database.
    3. Implementing all the HTTP Services needed.
    4. Call Services using Knockout.js.

    SQL Database Part

    Here, you will find the scripts to create your database and table.

    Create Table

    CREATE TABLE [dbo].[User](
    [UserID] [int] IDENTITY(1,1) NOT NULL,
    [Fname] [varchar](50) NULL,
    [Lname] [varchar](50) NULL) ON [PRIMARY]
    

    Create Your MVC application

    Open Visual Studio and select File >> New Project.

    The “New Project” window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.

    Next, a new window will pop up for selecting the template. We are going to choose Web API template and click OK.

    After creating our project, we are going to add the ADO.NET Entity Data model.

    Adding ADO.NET Entity Data Model

    To add the ADO.NET Entity Framework, right click on the project name, click Add > Add New Item. A dialog box will pop up. Inside this box, select Visual C# Data then ADO.NET Entity Data Model, and enter a name for your Dbcontext model, such as Customer Model, and finally click Add.

    Next, we need to choose model contain for the EF Designer from the database.

    As you can see below, we need to select a server name, then, via a drop down list, connect it to a database panel. You should choose your database name. Finally, click OK.

    Now, the Entity Data Model Wizard window will pop up for choosing an object which we need to use. In our case, we are going to choose Customers table and click Finish. Finally, we see that the EDMX model generates a Customer class.

     

    Create a Controller

    Now, we are going to create a controller. Right click on the controller’s folder > Add > Controller> selecting Web API 2 Controller with actions using Entity Framework > click Add.

    In the snapshot given below, we are providing three important parameters:

    1. Model class: Customer represents the entity that should be used for CRUD operations.
    2. Data context class: used to establish a connection with the database.
    3. Finally, we need to name our controller (in this case Customers Controller).

    As we already know, Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients including browsers and mobile devices.

    It has four methods:

    1. Get is used to select data.
    2. Post is used to create or insert data.
    3. Put is used to update data.
    4. Delete is used to delete data.

    UsersController.cs

    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.Web.Http.Description;
    using UserAPI.Models;
    
    namespace UserAPI.Controllers
    {
        public class UsersController : ApiController
        {
            private RegistrationEntities db = new RegistrationEntities();
    
            // GET: api/Users
            public List GetUsers()
            {
                dynamic user = db.Users.ToList();
                List userList = new List();
                foreach (var name in user)
                {
                    UserDTO dto = new UserDTO();
                    dto.UserId = name.UserId;
                    dto.Fname = name.Fname;
                    dto.Lname = name.Lname;
                    userList.Add(dto);
                }
                return userList;
            }
    
            // GET: api/Users/5
            [ResponseType(typeof(UserDTO))]
            public async Task GetUser(int id)
            {
                //var user = db.Users.Where(u => u.UserId == id).ToList().SingleOrDefault(u => u.UserId == id);
                var user = db.Users.Where(u => u.UserId == id).FirstOrDefaultAsync();
    
                if (user == null)
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
             Content = new StringContent(string.Format("No User with Id={0}", id)),
                        ReasonPhrase = "User ID not found"
                    };
                    throw new HttpResponseException(resp);
                }
                return Ok(user);
            }
    
            // PUT: api/Users/5
            [ResponseType(typeof(void))]
            public async Task PutUser(int id, User user)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                if (id != user.UserId)
                {
                    return BadRequest();
                }
    
                db.Entry(user).State = EntityState.Modified;
    
                try
                {
                    await db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return StatusCode(HttpStatusCode.NoContent);
            }
    
            // POST: api/Users
            [ResponseType(typeof(UserDTO))]
            public async Task PostUser(User user)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                db.Users.Add(user);
                await db.SaveChangesAsync();
    
                var dto = new UserDTO()
                {
                    UserId = user.UserId,
                    Fname = user.Fname,
                    Lname = user.Lname
                };
    
                return CreatedAtRoute("DefaultApi", new { id = user.UserId }, dto);
            }
    
            // DELETE: api/Users/5
            [ResponseType(typeof(UserDTO))]
            public async Task DeleteUser(int id)
            {
                User = await db.Users.FindAsync(id);
                if (user == null)
                {
                    return NotFound();
                }
    
                db.Users.Remove(user);
                await db.SaveChangesAsync();
    
                var dto = new UserDTO()
                {
                    UserId = user.UserId,
                    Fname = user.Fname,
                    Lname = user.Lname
                };
    
                return Ok(dto);
            }
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private bool UserExists(int id)
            {
                return db.Users.Count(e => e.UserId == id) > 0;
            }
        }
    }
    

    Calling Services Using Knockout.js

    First of all, we need to install Knockout.js. From the solution explorer panel, right click on references > Manage NuGet Packages…