CRUD Operation Using Web API In ASP.NET MVC

Here, we will learn about creating Web API in ASP.NET MVC and will also perform the crud operation using Web API. Web API is very important in order to share data from the world.

Prerequisites

  • Basic knowledge of ASP.NET MVC
  • Basic knowledge of Web API
  • Basic knowledge of jQuery

Now, create a new project in ASP.NET Web Application and select the Web API framework when creating the project.

crud-operation-using-web-api-in-asp-net-mvc-1

Now it will create a new Web API project in our application.

We will now add the new Web API controller. To create a new controller by right click on the controller folder.

crud-operation-using-web-api-in-asp-net-mvc-3

Choose a Web API controller from it and name it as CrudAPI.

crud-operation-using-web-api-in-asp-net-mvc-2

We will use the code-first approach for creating the database and tables. So if you have no idea of it then you can see it from here.

Install-Package EntityFramework

Open the package manager console and type the following command.

Now, in the Models folder create a Context.cs file and Customers.cs file

Code for Customers.cs file

public class Customers
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

Code for Context.cs file

public class Context : DbContext
    {
        public Context() : base("DefaultConnection")
        {
        }
        public DbSet<Customers> Customers { get; set; }
    }

Open the Web. Config file presents at root folder and adds the connection string in it.

<connectionStrings>
    <add name="DefaultConnection" connectionString="Server=DESKTOP-CGB025P;Initial Catalog=DemoDB;Persist Security Info=False;User ID=sa;Password=*****;MultipleActiveResultSets=True;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Open the package manager console and type the following command in it.

Enable-Migrations
Add-Migration Initial
Update-Database

Open the CrudAPIController and add the code in it.

public class CrudAPIController : ApiController
    {
        private readonly Context _context = new Context();
        [HttpGet]
        public IEnumerable<Customers> Get()
        {
            return _context.Customers.AsEnumerable();
        }
        [HttpGet]
        public Customers Get(int id)
        {
            Customers Customers = _context.Customers.Find(id);
            if (Customers == null)
            {
                return null;
            }
            return Customers;
        }
        [HttpPost]
        public HttpResponseMessage Post(Customers Customers)
        {
            if (ModelState.IsValid)
            {
                _context.Customers.Add(Customers);
                _context.SaveChanges();
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Customers);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Customers.Id }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
        [HttpPost]
        [Route("api/crudapi/put")]
        public HttpResponseMessage Put(Customers Customers)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            _context.Entry(Customers).State = EntityState.Modified;
            _context.SaveChanges();
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        [HttpDelete]
        public HttpResponseMessage Delete(int id)
        {
            Customers Customers = _context.Customers.Find(id);
            if (Customers == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            _context.Customers.Remove(Customers);
            _context.SaveChanges();
            return Request.CreateResponse(HttpStatusCode.OK, Customers);
        }
        protected override void Dispose(bool disposing)
        {
            _context.Dispose();
            base.Dispose(disposing);
        }
    }

Open the Index.cshtml file present in Home folder and add the code in it.

<div class="row">
    <div class="col-md-12">
        <table class="table table-bordered table-hover">
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Actions</th>
            </tr>
            <tbody class="tbody"></tbody>
        </table>
    </div>
    <div class="col-md-12">
        <div class="form-group">
            <lable>Name</lable>
            <input type="text" id="txtName" class="form-control empty" />
            <input type="hidden" id="hdnId" class="form-control empty" />
        </div>
        <div class="form-group">
            <lable>Email</lable>
            <input type="email" id="txtEmail" class="form-control empty" />
        </div>
        <div class="form-group">
            <button onclick="addCustomer()" id="btnAdd" class="btn btn-success">Add Data</button>
            <button onclick="editSaveCustomer()" id="btnEdit" class="btn btn-success">Save Edit Data</button>
        </div>
    </div>
</div>

<script>
    GetAllData();
    function GetAllData() {
        $('#btnEdit').hide();
        $('#btnAdd').show();
        $.ajax({
            url: 'http://localhost:63350/api/crudapi',
            type: 'GET',
            success: function (res) {
                $('.tbody').html('');
                var html = "";
                $.each(res, function (index, item) {
                    html += '<tr>';
                    html += '<td>' + item.Name + '</td>';
                    html += '<td>' + item.Email + '</td>';
                    html += '<td><a href="#" onclick=editCustomer(' + item.Id + ')>Edit</a><a href="#" onclick=deleteCustomer(' + item.Id + ')>Delete</a></td>';
                    html += '</tr>';
                });
                $('.tbody').append(html);
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
    function editCustomer(id) {
        $.ajax({
            url: 'http://localhost:63350/api/crudapi',
            type: 'GET',
            data: { 'id': id },
            success: function (res) {
                if (res != null) {
                    $('#txtName').val(res.Name);
                    $('#txtEmail').val(res.Email);
                    $('#hdnId').val(res.Id);
                }
                $('#btnEdit').show();
                $('#btnAdd').hide();
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
    function deleteCustomer(id) {
        $('#btnEdit').hide();
        $('#btnAdd').show();
        if (confirm("Are you sure, you want to delete the data?")) {
            $.ajax({
                url: 'http://localhost:63350/api/crudapi/' + id,
                type: 'DELETE',
                success: function (res) {
                    if (res != null) {
                        GetAllData();
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        }
    }
    function addCustomer() {
        var customers = {
            Name: $('#txtName').val(),
            Email: $('#txtEmail').val()
        };
        $.ajax({
            url: 'http://localhost:63350/api/crudapi',
            type: 'POST',
            data: customers,
            success: function (res) {
                if (res != null) {
                    GetAllData();
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
    function editSaveCustomer() {
         var customers = {
            Id: $('#hdnId').val(),
            Name: $('#txtName').val(),
            Email: $('#txtEmail').val()
        };
        $.ajax({
            url: 'http://localhost:63350/api/crudapi/put',
            type: 'POST',
            data: customers ,
            success: function (res) {
                $('#btnEdit').hide();
                $('#btnAdd').show();
                $('.empty').val('');
                if (res != null) {
                    GetAllData();
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
</script>

Open the _Layout.cshtml file and add the code in it.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
                    <li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @RenderSection("scripts", required: false)
</body>
</html>

Output:

output

2 Comments

  1. Faisal Pathan

    No, I don’t have a repo fot this article, but you can follow steps it will works, and if not for some reason let me know I’ll help.

    0
    0
    Reply
  2. Ahmadali latif

    please download link provide this code article

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories