AngularJS > Single Page Application

Single Page Application Web API creation in AngularJS

How to create an Web API that can be consumed in Single Page Application?


In previous posts, we learnt about Single Page Application template. In this post, we shall learn how to create an ASP.NET Web API that we will consume in our Single Page Application.

Database structure

The database structure we are going to use in this Single Page Application demonstration is following. The database is of LocalDB type that Visual Studio generates automatically. However we can create new SQL Server database and change the web.config connectionString settings as shown in this post.

As we can see that in below image, we have a PersonalDetails database table with 5 columns where AutoId is the auto increment field and primary key. Below is the script to create the database table.

CREATE TABLE [dbo].[PersonalDetails] (
    [AutoId]    INT          IDENTITY (1, 1) NOT NULL,
    [FirstName] VARCHAR (50) NULL,
    [LastName]  VARCHAR (50) NULL,
    [Age]       INT          NULL,
    [Active]    BIT          NULL,
    PRIMARY KEY CLUSTERED ([AutoId] ASC)
);

Single Page Application demo database structure

Once the database is setup and web.config file is changed (only if you are using a separate SQL Server database), it is time to create a model for this database table.

Creating ASP.NET Web API Model

Learn how to create a new model based on database table in ASP.NET MVC and your model code should look like below

PersonalDetail.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class PersonalDetail
    {
        [Key]
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public int AutoId { get; set; }

        [StringLength(20, MinimumLength = 4, ErrorMessage = "Must be at least 4 characters long.")]
        [Display(Name= "First Name")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Please write your LastName")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        public int? Age { get; set; }

        [Display(Name = "Is Active?")]
        public bool? Active { get; set; }
    }
}

After creating the model, right click your project and select Build/Rebuild to build the entire project.

ASP.NET Web API Controller code

Once the model is created, it is time to create a new PersonalDetailsController. Before you do that, you may need to change the ~/Global.asax file as written in this post.

We have already learnt how to Create new ASP.NET Web API in ASP.NET MVC Project, follow the exact step and you should have your API controller ready.

Below is the exact copy-paste of the Api controller generated by Visual Studio for above database structure.

PersonalDetailsController.cs code

using System;
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 SinglePageWebApplication.Models;
using WebApplication1.Models;

namespace SinglePageWebApplication.Controllers
{
    public class PersonalDetailsController : ApiController
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: api/PersonalDetails
        public IQueryable<PersonalDetail> GetPersonalDetails()
        {
            return db.PersonalDetails;
        }

        // GET: api/PersonalDetails/5
        [ResponseType(typeof(PersonalDetail))]
        public async Task<IHttpActionResult> GetPersonalDetail(int id)
        {
            PersonalDetail personalDetail = await db.PersonalDetails.FindAsync(id);
            if (personalDetail == null)
            {
                return NotFound();
            }

            return Ok(personalDetail);
        }

        // PUT: api/PersonalDetails/5
        [ResponseType(typeof(void))]
        public async Task<IHttpActionResult> PutPersonalDetail(int id, PersonalDetail personalDetail)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != personalDetail.AutoId)
            {
                return BadRequest();
            }

            db.Entry(personalDetail).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PersonalDetailExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/PersonalDetails
        [ResponseType(typeof(PersonalDetail))]
        public async Task<IHttpActionResult> PostPersonalDetail(PersonalDetail personalDetail)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.PersonalDetails.Add(personalDetail);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = personalDetail.AutoId }, personalDetail);
        }

        // DELETE: api/PersonalDetails/5
        [ResponseType(typeof(PersonalDetail))]
        public async Task<IHttpActionResult> DeletePersonalDetail(int id)
        {
            PersonalDetail personalDetail = await db.PersonalDetails.FindAsync(id);
            if (personalDetail == null)
            {
                return NotFound();
            }

            db.PersonalDetails.Remove(personalDetail);
            await db.SaveChangesAsync();

            return Ok(personalDetail);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool PersonalDetailExists(int id)
        {
            return db.PersonalDetails.Count(e => e.AutoId == id) > 0;
        }
    }
}

After creating the controller, rebuild the project once again. Run your application and go to API menu from the home page and you should see something like this (the action methods of PersonalDetailsController are exposed as API).

ASP.NET Web API reference

If you have reached this far, you are almost done for the server side code. Good job.

Now let's create client side, the magic code of Single Page Application.

 Views: 16523 | Post Order: 71




Write for us






Hosting Recommendations