Tuesday, 4 February 2014

CRUD operation using Modal dialog in ASP.NET MVC

In this article I am going to explain how to add, edit, delete and find [CRUD (Create, Retrieve, Update, Delete)] records using razor view engine in ASP.NET MVC3 or above version. It will display modal dialog if the JavaScript is turned on otherwise a simple view page, when we try to add and edit the records of student.

Please follow the steps given below to create an application that allows user to add, edit, delete and find records of student.

Open Microsoft Visual Studio 2010 - Select New Project - Select Web from the Installed Templates - Select ASP.NET MVC3 or MVC4 Web Application - Enter the project name Modal_CRUD_MVC in the Name textbox - Click OK.

After select the project you can see the following dialog box:

Select Empty from the Select a template option - Select Razor view engine - Click OK.

Add the following Modal classes (Student and StudentContext) in your Model folder:

Student class represents the table structure in the database and StudentContext Students property represents the name of table and data of the students in the database.

    public class Student

    {

        public int StudentID {  getset; }

        public string Name { get; set; }

        public string Age { get; set; }

        public string State { get; set; }

        public string Country { get; set; }

    }

    public class StudentContext : DbContext

    {

        public DbSet<Student> Students

        {

            get;

            set;

        }

    }

 

Also include Entity framework reference in your project because in this application we are going to use entity framework code first model to add, edit, delete and find records from the database. To include entity framework dll, follow these steps:

Go to Project - Manage NuGet Packages - Enter entity framework in the search textbox and search online.

You will find latest version of Entity framework version.

You also have to configure your web.config file for the implementation of this project. Add the connectionStrings element under configuration tag:

  <connectionStrings>

    <add name="StudentContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=StudentDb;Integrated Security=true;" providerName="System.Data.SqlClient" />

  </connectionStrings>

 

Add a Controller in your project and edit the controller name as HomeController as shown in the figure below:

After adding HomeController, add an Index view into your project:

Edit the Index view and add the following code as given below. Also include these files (jquery-ui.min.css, jquery-1.7.1.min.js, jquery-ui-1.8.20.min.js) in your project.

@model IEnumerable<Modal_CRUD_MVC.Models.Student>

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <link href="@Url.Content("~/Content/themes/base/minified/jquery-ui.min.css")" rel="stylesheet" type="text/css" />

    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {

 

            $.ajaxSetup({ cache: false });

           

            $("#openDialog").live("click", function (e) {

                e.preventDefault();

                var url = $(this).attr('href');

 

                $("#dialog-edit").dialog({

                    title: 'Add Student',

                    autoOpen: false,

                    resizable: false,

                    height: 355,

                    width: 400,

                    show: { effect: 'drop', direction: "up" },

                    modal: true,

                    draggable: true,

                    open: function (event, ui) {

                        $(this).load(url);

                    },

                    close: function (event, ui) {

                        $(this).dialog('close');

                    }

                });

 

                $("#dialog-edit").dialog('open');

                return false;

            });

 

            $(".editDialog").live("click", function (e) {

                var url = $(this).attr('href');

                $("#dialog-edit").dialog({

                    title: 'Edit Customer',

                    autoOpen: false,

                    resizable: false,

                    height: 355,

                    width: 400,

                    show: { effect: 'drop', direction: "up" },

                    modal: true,

                    draggable: true,

                    open: function (event, ui) {

                        $(this).load(url);

 

                    },

                    close: function (event, ui) {

                        $(this).dialog('close');

                    }

                });

 

                $("#dialog-edit").dialog('open');

                return false;

            });

 

            $(".confirmDialog").live("click", function (e) {

 

                var url = $(this).attr('href');

                $("#dialog-confirm").dialog({

                    autoOpen: false,

                    resizable: false,

                    height: 170,

                    width: 350,

                    show: { effect: 'drop', direction: "up" },

                    modal: true,

                    draggable: true,

                    buttons: {

                        "OK": function () {

                            $(this).dialog("close");

                            window.location = url;

 

                        },

                        "Cancel": function () {

                            $(this).dialog("close");

 

                        }

                    }

                });

                $("#dialog-confirm").dialog('open');

                return false;

            });

 

            $(".viewDialog").live("click", function (e) {

                var url = $(this).attr('href');

                $("#dialog-view").dialog({

                    title: 'View Customer',

                    autoOpen: false,

                    resizable: false,

                    height: 355,

                    width: 400,

                    show: { effect: 'drop', direction: "up" },

                    modal: true,

                    draggable: true,

                    open: function (event, ui) {

                        $(this).load(url);

 

                    },

                    buttons: {

                        "Close": function () {

                            $(this).dialog("close");

 

                        }

                    },

                    close: function (event, ui) {

                        $(this).dialog('close');

                    }

                });

 

                $("#dialog-view").dialog('open');

                return false;

            });

 

            $("#btncancel").live("click", function (e) {

                $("#dialog-edit").dialog('close');

 

            });

        });  

    </script>

</head>

<body>

    <table align="center" width="800px">

        <tr>

            <td>

                @Html.ActionLink("Create New", "AddEditRecord", "Home", null, new { @id = "openDialog" })

            </td>

        </tr>

    </table>

    <table cellpadding="10" style="border: 1px solid black; font-family: Verdana;" align="center"

        width="800px">

        <tr>

            <th>

                @Html.DisplayNameFor(model => model.Name)

            </th>

            <th>

                @Html.DisplayNameFor(model => model.Age)

            </th>

            <th>

                @Html.DisplayNameFor(model => model.State)

            </th>

            <th>

                @Html.DisplayNameFor(model => model.Country)

            </th>

            <th>

            </th>

        </tr>

        @foreach (var item in Model)

        {

            <tr>

                <td align="center">

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

                </td>

                <td align="center">

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

                </td>

                <td align="center">

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

                </td>

                <td align="center">

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

                </td>

                <td>

                    @Html.ActionLink("Edit", "AddEditRecord", new { id = item.StudentID }, new { @class = "editDialog" })|

                    @Html.ActionLink("Details", "Details", new { id = item.StudentID }, new { @class = "viewDialog" }) |

                    @Html.ActionLink("Delete", "DeleteRecord", new { id = item.StudentID }, new { @class = "confirmDialog" })

                </td>

            </tr>

        }

    </table>

    <div id="dialog-confirm" style="display: none">

        <p>

            <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>

            Are you sure to delete ?

        </p>

    </div>

    <div id="dialog-edit" style="display: none">

    </div>

    <div id="dialog-view" style="display: none">

    </div>

</body>

</html>

 

I have put all the code necessary to perform add, edit, delete and find records of the students in the Index view. In this project we do not have any Layout or Master page.

After including files in the project, your solution explorer might something look like this:

Add a partial view _StudentData in Views - Home folder.

Edit the _StudentData partial view as below:

@model Modal_CRUD_MVC.Models.Student

@using (Ajax.BeginForm("AddEditRecord", "Home", new AjaxOptions{ HttpMethod = "POST", UpdateTargetId = "studentDialog" }))

{

    @Html.ValidationSummary(true)

 

    <fieldset>

        <legend>Student</legend>

        @if (ViewBag.IsUpdate == true)

        {

            @Html.HiddenFor(model => model.StudentID)

        }

        <div class="editor-label">

            @Html.LabelFor(model => model.Name)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Name)

            @Html.ValidationMessageFor(model => model.Name)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Age)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Age)

            @Html.ValidationMessageFor(model => model.Age)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.State)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.State)

            @Html.ValidationMessageFor(model => model.State)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Country)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Country)

            @Html.ValidationMessageFor(model => model.Country)

        </div>

        <p>

            @if (ViewBag.IsUpdate == true)

            {

                <input type="submit" value="Update" id="btnUpdate" name="cmd" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

            }

            else

            {

                <input type="submit" value="Save" id="btnSave" name="cmd" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

            }

            <input type="button" value="Cancel" id="btncancel" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

        </p>

    </fieldset>

}

 

Also add StudentData view in the same folder Views - Home. This view will response by the controller to the browser if the JavaScript is turned off otherwise the above partial view will display in a modal dialog to the user.

@model Modal_CRUD_MVC.Models.Student

@using (Html.BeginForm("AddEditRecord", "Home"))

{

    @Html.ValidationSummary(true)

 

    <fieldset>

        <legend>Student</legend>

        @if (ViewBag.IsUpdate == true)

        {

            @Html.HiddenFor(model => model.StudentID)

        }

        <div class="editor-label">

            @Html.LabelFor(model => model.Name)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Name)

            @Html.ValidationMessageFor(model => model.Name)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Age)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Age)

            @Html.ValidationMessageFor(model => model.Age)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.State)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.State)

            @Html.ValidationMessageFor(model => model.State)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Country)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Country)

            @Html.ValidationMessageFor(model => model.Country)

        </div>

        <p>

            @if (ViewBag.IsUpdate == true)

            {

                <input type="submit" value="Update" id="btnUpdate" name="cmd" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

            }

            else

            {

                <input type="submit" value="Save" id="btnSave" name="cmd" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

            }

            @Html.ActionLink("Back to List", "Index")

        </p>

    </fieldset>

}

 

Add a partial view _StudentDetails in Views - Home folder.

Edit the _StudentDetails partial view as below:

@model Modal_CRUD_MVC.Models.Student

 

<fieldset>

    <legend>Student</legend>

 

    <div class="display-label">

         @Html.DisplayNameFor(model => model.Name)

    </div>

    <div class="display-field">

        @Html.DisplayFor(model => model.Name)

    </div>

 

    <div class="display-label">

         @Html.DisplayNameFor(model => model.Age)

    </div>

    <div class="display-field">

        @Html.DisplayFor(model => model.Age)

    </div>

 

    <div class="display-label">

         @Html.DisplayNameFor(model => model.State)

    </div>

    <div class="display-field">

        @Html.DisplayFor(model => model.State)

    </div>

 

    <div class="display-label">

         @Html.DisplayNameFor(model => model.Country)

    </div>

    <div class="display-field">

        @Html.DisplayFor(model => model.Country)

    </div>

</fieldset>

 

Add and Edit StudentDetails in Views - Home folder.

The purpose of adding StudentDetails view is same as I have explained above for StudentData view.

@model Modal_CRUD_MVC.Models.Student

 

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>StudentDetails</title>

</head>

<body>

    <fieldset>

        <legend>Student</legend>

   

        <div class="display-label">

             @Html.DisplayNameFor(model => model.Name)

        </div>

        <div class="display-field">

            @Html.DisplayFor(model => model.Name)

        </div>

   

        <div class="display-label">

             @Html.DisplayNameFor(model => model.Age)

        </div>

        <div class="display-field">

            @Html.DisplayFor(model => model.Age)

        </div>

   

        <div class="display-label">

             @Html.DisplayNameFor(model => model.State)

        </div>

        <div class="display-field">

            @Html.DisplayFor(model => model.State)

        </div>

   

        <div class="display-label">

             @Html.DisplayNameFor(model => model.Country)

        </div>

        <div class="display-field">

            @Html.DisplayFor(model => model.Country)

        </div>

    </fieldset>

    <p>

        @Html.ActionLink("Edit", "Edit", new { id = Model.StudentID }, new { @class = "editDialog" }) |

        @Html.ActionLink("Back to List", "Index")

    </p>

</body>

</html>

 

I have finished Model and View portion. Now I am going to explain about the HomeController and its Action methods which are necessary in order to run our application.

Index action returns a View along with the list of students:

    public class HomeController : Controller

    {

        StudentContext db = new StudentContext();

 

        public ActionResult Index()

        {

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

        }

    }

 

Add the AddEditRecord action with the parameter (id) which can be either null or not null. If the id parameter is null it will return empty _StudentData or StudentData, partial view or View respectively otherwise it will find the record of student on the basis of id and passes the student model to the view in order to update the student details.

Here I am also creating a dynamic property ViewBag.IsUpdate to change the button type in view. If the IsUpdate is true it will set button text as Update and if IsUpdate is false then it will be set as Save.

 [HttpGet]

        public ActionResult AddEditRecord(int? id)

        {

            if (Request.IsAjaxRequest())

            {

                if (id != null)

                {

                    ViewBag.IsUpdate = true;

                    Student student = db.Students.Where(m => m.StudentID == id).FirstOrDefault();

                    return PartialView("_StudentData", student);

                }

                ViewBag.IsUpdate = false;

                return PartialView("_StudentData");

            }

            else

            {

                if (id != null)

                {

                    ViewBag.IsUpdate = true;

                    Student student = db.Students.Where(m => m.StudentID == id).FirstOrDefault();

                    return PartialView("StudentData", student);

                }

                ViewBag.IsUpdate = false;

                return View("StudentData");

            }

        }

 

Add the AddEditRecord action which is of HttpPost type to add or update student record. If the cmd contains Save it will add the record of student in the database otherwise update the data of student in the database.

[HttpPost]

        public ActionResult AddEditRecord(Student student, string cmd)

        {

            if (ModelState.IsValid)

            {

                if (cmd == "Save")

                {

                    try

                    {

                        db.Students.Add(student);

                        db.SaveChanges();

                        return RedirectToAction("Index");

                    }

                    catch { }

                }

                else

                {

                    try

                    {

                        Student stud = db.Students.Where(m => m.StudentID == student.StudentID).FirstOrDefault();

                        if (stud != null)

                        {

                            stud.Name = student.Name;

                            stud.Age = student.Age;

                            stud.State = student.State;

                            stud.Country = student.Country;

                            db.SaveChanges();

                        }

                        return RedirectToAction("Index");

                    }

                    catch { }

                }

            }

 

            if (Request.IsAjaxRequest())

            {

                return PartialView("_StudentData", student);

            }

            else

            {

                return View("StudentData", student);

            }

        }

 

To delete the record of students add the DeleteRecord action in the HomeController. This will delete the record of a student from the database on the basis of id.

public ActionResult DeleteRecord(int id)

        {

            Student student = db.Students.Where(m => m.StudentID == id).FirstOrDefault();

            if (student != null)

            {

                try

                {

                    db.Students.Remove(student);

                    db.SaveChanges();

                }

                catch { }

            }

            return RedirectToAction("Index");

        }

 

To view the details of student, add the Details action in your HomeController. This will display the details of a student on the basis of id.

public ActionResult Details(int id)

        {

            Student student = db.Students.Where(m => m.StudentID == id).FirstOrDefault();

            if (student != null)

            {

                if (Request.IsAjaxRequest())

                {

                    return PartialView("_StudentDetails", student);

                }

                else

                {

                    return View("StudentDetails", student);

                }

            }

            return View("Index");

        }

 

Now both coding and design part is over. To test an application, run or debug your application:

 I have added few records during coding. You can add student records by using Create New option.

To edit records, just press edit link given for each students in a row.

If the JavaScript is turned off, you cannot use modal dialog to add and edit the records of students, then in that case you can use StudentData view to add and edit the records.

To delete the record of student, use Delete link.

Thanks for reading this article. You can enter your valuable comments and suggestion to improve this article in the comment box.

 

3 comments:

Anonymous said...

nice one. helps a lot.
thanks.

Wright Petter said...

Great Article
Hire Angular 5 Developer
Angular 5 Training in CHennai
Angular 5 Training in Chennai.

Patrick Co Eban said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.