Top Banner

of 18

CRUD Operation Using Modal Dialog in MVC

Jun 04, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    1/18

    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 2010Select New ProjectSelect Webfrom the Installed Templates

    Select ASP.NET MVC3 or MVC4 Web ApplicationEnter the project name Modal_CRUD_MVC in the

    Name textboxClick OK.

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

    Select Emptyfrom the Select a template optionSelect Razorview engineClick OK.

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    2/18

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

    Studentclass represents the table structure in the database and StudentContextStudents property

    represents the name of table and data of the students in the database.

    publicclassStudent{

    publicintStudentID { get; set; }publicstringName { get; set; }publicstringAge { get; set; }publicstringState { get; set; }publicstringCountry { get; set; }

    }publicclassStudentContext: DbContext{

    publicDbSet Students{

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    3/18

    get;set;

    }}

    Also include Entity framework reference in your project because in this application we are going to useentity framework code first model to add, edit, delete and find records from the database. To include

    entity framework dll, follow these steps:

    Go to ProjectManage NuGet PackagesEnter entity frameworkin 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

    connectionStringselement under configuration tag:

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    4/18

    Add a Controller in your project and edit the controller name as HomeControlleras shown in the figure

    below:

    After adding HomeController, add an Indexview into your project:

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    5/18

    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@{

    Layout = null;}

    Index

    $(document).ready(function() {

    $.ajaxSetup({ cache: false});

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    6/18

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

    e.preventDefault();varurl = $(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');returnfalse;

    });

    $(".editDialog").live("click", function(e) {varurl = $(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');returnfalse;

    });

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

    varurl = $(this).attr('href');$("#dialog-confirm").dialog({

    autoOpen: false,resizable: false,height: 170,width: 350,

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    7/18

    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');returnfalse;

    });

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

    varurl = $(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');returnfalse;

    });

    $("#btncancel").live("click", function(e) {$("#dialog-edit").dialog('close');

    });});

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    8/18

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

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

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

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

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

    @foreach(varitem inModel){

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

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

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

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

    @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"})

    }

    Are you sure to delete ?

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    9/18

    I have put all the code necessary to perform add, edit, delete and find records of the students in the

    Indexview. 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_StudentDatain ViewsHome folder.

    Content folder base includes css

    files.

    Script folder includes two JavaScript

    files.

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    10/18

    Edit the _StudentDatapartial view as below:

    @model Modal_CRUD_MVC.Models.Student@using(Ajax.BeginForm("AddEditRecord", "Home", newAjaxOptions{ HttpMethod = "POST",UpdateTargetId = "studentDialog"})){

    @Html.ValidationSummary(true)

    Student@if(ViewBag.IsUpdate == true){

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

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

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

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

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

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

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    11/18

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

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

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

    @if(ViewBag.IsUpdate == true){

    }else{

    }

    }

    Also add StudentDataview in the same folder ViewsHome. 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)

    Student@if(ViewBag.IsUpdate == true){

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

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

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

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

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

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    12/18

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

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

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

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

    @if(ViewBag.IsUpdate == true){

    }else{

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

    }

    Add a partial view_StudentDetailsin ViewsHome folder.

    Edit the _StudentDetailspartial view as below:

    @model Modal_CRUD_MVC.Models.Student

    Student

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

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

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

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

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    13/18

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

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

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

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

    Add and Edit StudentDetailsin ViewsHome 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;

    }

    StudentDetails

    Student

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

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

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

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

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

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

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    14/18

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

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

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

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

    I have finished Model and View portion. Now I am going to explain about the HomeControllerand its

    Actionmethods which are necessary in order to run our application.

    Indexaction returns a View along with the list of students:

    publicclassHomeController: Controller{

    StudentContextdb = newStudentContext();

    publicActionResultIndex(){

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

    }

    Add the AddEditRecordaction 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]publicActionResultAddEditRecord(int? id){

    if(Request.IsAjaxRequest()){

    if(id != null){

    ViewBag.IsUpdate = true;Studentstudent = db.Students.Where(m => m.StudentID ==

    id).FirstOrDefault();returnPartialView("_StudentData", student);

    }ViewBag.IsUpdate = false;returnPartialView("_StudentData");

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    15/18

    }else{

    if(id != null){

    ViewBag.IsUpdate = true;Studentstudent = db.Students.Where(m => m.StudentID ==

    id).FirstOrDefault();returnPartialView("StudentData", student);

    }ViewBag.IsUpdate = false;returnView("StudentData");

    }}

    Add the AddEditRecordaction which is of HttpPosttype 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]publicActionResultAddEditRecord(Studentstudent, stringcmd){

    if(ModelState.IsValid){

    if(cmd == "Save"){

    try{

    db.Students.Add(student);db.SaveChanges();returnRedirectToAction("Index");

    }catch{ }

    }else{

    try{

    Studentstud = 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();}returnRedirectToAction("Index");

    }catch{ }

    }}

    if(Request.IsAjaxRequest())

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    16/18

    {returnPartialView("_StudentData", student);

    }else{

    returnView("StudentData", student);}

    }

    To delete the record of students add the DeleteRecordaction in the HomeController. This will delete

    the record of a student from the database on the basis of id.

    publicActionResultDeleteRecord(intid){

    Studentstudent = db.Students.Where(m => m.StudentID == id).FirstOrDefault();if(student != null){

    try

    {db.Students.Remove(student);db.SaveChanges();

    }catch{ }

    }returnRedirectToAction("Index");

    }

    To view the details of student, add the Detailsaction in your HomeController. This will display the

    details of a student on the basis of id.

    publicActionResultDetails(intid){

    Studentstudent = db.Students.Where(m => m.StudentID == id).FirstOrDefault();if(student != null){

    if (Request.IsAjaxRequest()){

    returnPartialView("_StudentDetails", student);}else{

    returnView("StudentDetails", student);}

    }returnView("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 Newoption.

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    17/18

    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.

  • 8/13/2019 CRUD Operation Using Modal Dialog in MVC

    18/18

    To delete the record of student, use Deletelink.

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

    article in the comment box.