articles

Home / DeveloperSection / Articles / CRUD Operation Using Modal Dialog in ASP.NET MVC

CRUD Operation Using Modal Dialog in ASP.NET MVC

CRUD Operation Using Modal Dialog in ASP.NET MVC

Chris Anderson235590 21-Jan-2013

CRUD Operation Using Modal Dialog in ASP.NET MVC

In this article I am going to explain how to complete add, update, delete and find OR CRUD (Create, Retrieve, Update, Delete) Operation using razor view engine in ASP.NET MVC3 or above version.

Here into this example, I will use modal dialog by using JavaScript to add, edit, delete and find operation.

Please follow the steps given below to create an application that allows the user to add, edit, delete and find records of the 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.

CRUD Operation Using Modal Dialog in ASP.NET MVC

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

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

CRUD Operation Using Modal Dialog in ASP.NET MVC

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 the table and data of the students in the database.

    public class Student

    {
        public int StudentID { get; set; }
        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.

CRUD Operation Using Modal Dialog in ASP.NET MVC

You will find the latest version of the Entity framework version.

You also have to configure your web.config file for the implementation of this project. Add the connectionStrings element under the 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:

CRUD Operation Using Modal Dialog in ASP.NET MVC

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

CRUD Operation Using Modal Dialog in ASP.NET MVC

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:

CRUD Operation Using Modal Dialog in ASP.NET MVC

Add a partial view _StudentData in Views Ã  Home folder.

CRUD Operation Using Modal Dialog in ASP.NET MVC

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 the 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 the StudentDetails view is the same as I have explained above for the 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 the Model and View portion. Now I am going to explain 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 the 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 records. If the cmd contains Save it will add the record of the student in the database otherwise update the data of students 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 adds 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 the 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 a few records during coding. You can add student records by using Create New option.

CRUD Operation Using Modal Dialog in ASP.NET MVC

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

CRUD Operation Using Modal Dialog in ASP.NET MVC

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

CRUD Operation Using Modal Dialog in ASP.NET MVC

To delete the record of the student, use the Delete link.

CRUD Operation Using Modal Dialog in ASP.NET MVC

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


Updated 03-Sep-2020
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By