Crud operation in ASP.NET MVC using Ajax

Hi everyone in this post I’m explaining about Crud operation in mvc using Ajax.

Description:

In this post I’ll explain full crud operation in mvc using ajax. we have post data using ajax in my previous post Ajax with ASP.NET MVC. AJAX (Asynchronous javascript and xml) is used basically  to exchange data with a server and updating parts of web page without reloading whole page. Ajax make sites very fast and  enables more interactive web application with the help of xml, html, css and javascript.

Get start:

 

Step 1:  Create table in a database

CREATE TABLE STUDENT

(

      Id INT IDENTITY(1,1)primary key,

      Name VARCHAR(150),

      Age INT,

      State VARCHAR(150),

      Country VARCHAR(80)

)

 

Step 2:  Open visual studio >> File >> New Project >> ASP.NET MVC 4 Web Application

Give the application name and click ok open a new window and select project type empty.

 

Step 3:  Now install entity framework from Manage NuGet Package.

Step 4:  Now add .edmx file in model folder for use db first approach learn more about db first approach read my previous post Crud operation in MVC using DB First-Approach.

Step 5: Download these bootstrap files and javascript liberary

<link href="@Url.Content("~/Content/bootstrap/css/bootstrap.min.css")" rel="stylesheet" />

<link href="@Url.Content("~/Content/bootstrap/css/bootstrap-theme.min.css")" rel="stylesheet" />

<link href="@Url.Content("~/Content/bootstrap/css/font-awesome.min.css")" rel="stylesheet" />

<script src="@Url.Content("~/Script/jquery-2.1.3.min.js")"></script>

<script src="@Url.Content("~/Script/jquery.unobtrusive-ajax.min.js")"></script>

<script src="@Url.Content("~/Script/bootstrap/js/bootstrap.min.js")"></script>

Step 6:  Now add HomeController

using CrudAjax.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace CrudAjax.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

 

        MyDBEntities db = new MyDBEntities();

 

        public ActionResult Index()

        {

            return View(db.STUDENTs.ToList());

        }

 

        public ActionResult Add()

        {

            return PartialView();

        }

 

        [HttpPost]

        public ActionResult Add(STUDENT model)

        {

            if (ModelState.IsValid)

            {

                db.STUDENTs.Add(model);

                db.SaveChanges();

            }

            return PartialView("_Detail", db.STUDENTs.ToList());

        }

 

        public ActionResult Edit(int id)

        {

            return PartialView(db.STUDENTs.Find(id));

        }

 

        [HttpPost]

        public ActionResult Edit(STUDENT model, int id)

        {

            if (ModelState.IsValid)

            {

                db.Entry(model).State = System.Data.Entity.EntityState.Modified;

                db.SaveChanges();

            }

            return PartialView("_Detail", db.STUDENTs.ToList());

        }

 

        public ActionResult Delete(int id)

        {

            db.STUDENTs.Remove(db.STUDENTs.Find(id));

            db.SaveChanges();

            return PartialView("_Detail", db.STUDENTs.ToList());

        }

    }

}

 

Step 7:  Now add Index View

@{

    ViewBag.Title = "Index";

}

 

<link href="@Url.Content("~/Content/bootstrap/css/bootstrap.min.css")" rel="stylesheet" />

<link href="@Url.Content("~/Content/bootstrap/css/bootstrap-theme.min.css")" rel="stylesheet" />

<link href="@Url.Content("~/Content/bootstrap/css/font-awesome.min.css")" rel="stylesheet" />

<script src="@Url.Content("~/Script/jquery-2.1.3.min.js")"></script>

<script src="@Url.Content("~/Script/jquery.unobtrusive-ajax.min.js")"></script>

<script src="@Url.Content("~/Script/bootstrap/js/bootstrap.min.js")"></script>

 

<div id="main-div">

    <div class="clearfix">&nbsp;</div>

    <div class="clearfix">&nbsp;</div>

    <div class="container">

        <a href="@Url.Action("Add", "Home")" id="Add" class = "btn btn-primary"><i class="glyphicon glyphicon-plus"></i>&nbsp;Create New</a>

        <div id="div-record">

            @Html.Partial("_Detail")

        </div>

    </div>

 

 

    <div class="modal fade" id="Add-Model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                    <h4 class="modal-title">New Student</h4>

                </div>

                <div class="divForAdd">

                </div>

            </div>

        </div>

    </div>

 

    <div class="modal fade" id="Edit-Model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                    <h4 class="modal-title">Update Student</h4>

                </div>

                <div class="divForUpdate">

                </div>

            </div>

        </div>

    </div>

</div>

 

Step 8:  Now Add three Partial view

1.       Add.cshtml:

@model CrudAjax.Models.STUDENT

@using (Ajax.BeginForm("Add", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "div-record", OnSuccess = "$('.close').click()" }))

{

    <div class="modal-body">

        <div class="row form-group">

            <div class="col-md-12">

                <div class="input-group">

                    <span class="input-group-addon"><i class="fa fa-user-plus"></i></span>

                    @Html.TextBoxFor(m => m.Name, new { @class = "form-control", @placeholder = "Username" })

                </div>

            </div>

        </div>

        <div class="row form-group">

            <div class="col-md-12">

                <div class="input-group">

                    <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>

                    @Html.TextBoxFor(m => m.Age, new { @class = "form-control", @placeholder = "Age" })

                </div>

            </div>

        </div>

        <div class="row form-group">

            <div class="col-md-12">

                <div class="input-group">

                    <span class="input-group-addon"><i class="fa fa-globe"></i></span>

                    @Html.TextBoxFor(m => m.State, new { @class = "form-control", @placeholder = "State" })

                </div>

            </div>

        </div>

        <div class="row form-group">

            <div class="col-md-12">

                <div class="input-group">

                    <span class="input-group-addon"><i class="fa fa-globe"></i></span>

                    @Html.TextBoxFor(m => m.Country, new { @class = "form-control", @placeholder = "Country" })

                </div>

            </div>

        </div>

    </div>

    <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i>&nbsp;Close</button>

        <button type="submit" class="btn btn-primary" name="cmd"><i class="fa fa-check"></i>&nbsp;Save</button>

    </div>

}

 

2.       Edit.cshtml

 

@model CrudAjax.Models.STUDENT

@using (Ajax.BeginForm("Edit", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "div-record", OnSuccess = "$('.close').click()" }))

{

    @Html.HiddenFor(m => m.Id)

    <div class="modal-body">

        <div class="row form-group">

            <div class="col-md-12">

                <div class="input-group">

                    <span class="input-group-addon"><i class="fa fa-user-plus"></i></span>

                    @Html.TextBoxFor(m => m.Name, new { @class = "form-control", @placeholder = "Username" })

                </div>

            </div>

        </div>

        <div class="row form-group">

            <div class="col-md-12">

                <div class="input-group">

                    <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>

                    @Html.TextBoxFor(m => m.Age, new { @class = "form-control", @placeholder = "Age" })

                </div>

            </div>

        </div>

        <div class="row form-group">

            <div class="col-md-12">

                <div class="input-group">

                    <span class="input-group-addon"><i class="fa fa-globe"></i></span>

                    @Html.TextBoxFor(m => m.State, new { @class = "form-control", @placeholder = "State" })

                </div>

            </div>

        </div>

        <div class="row form-group">

            <div class="col-md-12">

                <div class="input-group">

                    <span class="input-group-addon"><i class="fa fa-globe"></i></span>

                    @Html.TextBoxFor(m => m.Country, new { @class = "form-control", @placeholder = "Country" })

                </div>

            </div>

        </div>

    </div>

    <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i>&nbsp;Close</button>

        <button type="submit" class="btn btn-primary" name="cmd"><i class="fa fa-check"></i>&nbsp;Save Changes</button>

    </div>

}

 

3.       _Detail.cshtml

 

@model IList<CrudAjax.Models.STUDENT>

<div class="table-responsive">

    <table class="table table-bordered table-striped">

        <thead>

            <tr>

                <th>Name</th>

                <th>Age</th>

                <th>State</th>

                <th>Country</th>

                <th>Edit</th>

                <th>Delete</th>

            </tr>

        </thead>

        <tbody>

            @foreach (var item in Model)

            {

                <tr>

                    <td>

                        @Html.DisplayFor(modelItem => item.Name)

                    </td>

                    <td>

                        @Html.DisplayFor(modelItem => item.Age)

                    </td>

                    <td>

                        @Html.DisplayFor(modelItem => item.State)

                    </td>

                    <td>

                        @Html.DisplayFor(modelItem => item.Country)

                    </td>

                    <td>

                        <a href="@Url.Action("Edit", "Home", new { id = item.Id })" class = "editDialog"><i class="fa fa-pencil-square-o"></i>&nbsp;Edit</a>

                    </td>

                    <td>

                        @Ajax.ActionLink("Delete", "Delete", "Home", new { @id = item.Id }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div-record" }, new { @class = "fa fa-trash-o" })

                    </td>

                </tr>

            }

        </tbody>

    </table>

</div>

<script>

    $(document).ready(function () {

        $('#Add').click(function (event) {

            event.preventDefault();

            $.get(this.href, function (response) {

                $('.divForAdd').html(response);

            });

            $('#Add-Model').modal({

                backdrop: 'static',

            }, 'show');

        });

        $('.editDialog').click(function (event) {

            event.preventDefault();

            $.get(this.href, function (response) {

                $('.divForUpdate').html(response);

            });

            $('#Edit-Model').modal({

                backdrop: 'static',

            }, 'show');

        });

    });

</script>

 

Output:

1.       When click Create New User

        

 

2.       Here in the output I’m click to edit button

       

        I’m update this record Kamlakar Singh to Kamlakar

     

 

      Now change this record

    

 

3.       Here in the output I’m delete Kamlakar record

     

 

 

In my next post I’ll explain about TDD and ASP.NET MVC.

  1. Hi


    I meet this issue

    External component has thrown an exception.


    Can you share the code zip format thats helpful for me.

  1. I have used your exemple on my own work with my own model, so When I click to Url.Action it doesn't load the modal partialview but it try to redirect to controller's action ? what can i do ? I am using razor / mvc 5 thank you.

  1. Your MODEL directive is wrong.

    It should be expecting a LIST of students instead of a single student

    @model List<CRUDAjaxMVC.Models.STUDENT>

  1. The most complete article for beginers to understand how to use a modal in a MVC application. Thank's for your effort.  

Leave Comment