articles

Home / DeveloperSection / Articles / CRUD Operation Modal Popup uses Bootstrap in mvc

CRUD Operation Modal Popup uses Bootstrap in mvc

Rahul Pal69951 14-Dec-2017

Step 1:

  Open the Microsoft visual studio 2012 and select a new project Asp.net MVC4 application and enter the project name CRUDMVCApp and Click Button Ok

CRUD Operation Modal Popup uses Bootstrap in mvc

Step 2 : After selecting the project you can see the following Dialog Box

Select the Empty form the select template option and select Razor View Engine and click Ok

CRUD Operation Modal Popup uses Bootstrap in mvc

Step 3 : For Modal Class, right click on modal folder and select a class, in model classes we have to add a class For e.g. I am adding student class The student class represents a the table structure of the database

CRUD Operation Modal Popup uses Bootstrap in mvc

Here I’m defining a table structure of employee in employee class

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MvApp1.Models
{

    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string FatherName { get; set; }
        public string DOB { get; set; }
        public int MobileNo { get; set; }
        public int Age { get; set; }
        public string EmailId { get; set; }
    }

}

Step 4 :Also include entity framework because we are retrieving and storing the value in the database using Entity Framework To add Entity Framework in the app, right click on modal and name it EmployeeDbModal 

CRUD Operation Modal Popup uses Bootstrap in mvc

CRUD Operation Modal Popup uses Bootstrap in mvc


Step 5 :

After clicking on OK button Entity Data Modal Wizard PoP Up

CRUD Operation Modal Popup uses Bootstrap in mvc


step 6 : 

After clicking on the next button, click on the new connection string and select server name and select Windows authentication or SQL server authentication and the select a database, my  database is employed

CRUD Operation Modal Popup uses Bootstrap in mvc


step 7 : After Clicking Ok button, select a table which you want to use a table in the application and click on finish button

CRUD Operation Modal Popup uses Bootstrap in mvc


step 8 : After completing this part, let move to controller how to create a controller, right click on the controller Select controller and name it EmployeeController

CRUD Operation Modal Popup uses Bootstrap in mvc

step  9 : After clicking on the controller the Please Write a code for Create, Edit, update, View. In controller there is two Method, by default one get method which get the value and render the page and second is post is used to boost the value in the database, here we can declare the post in the controller

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvApp1.Models;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace MvApp1.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/
        EmployeeDBEntities EmpDb = new EmployeeDBEntities();//Here we are calling Entityframework,in which your selected table place


 //For View the Record
        public ActionResult EmployeeDetails()
        {
            var result = EmpDb.TblEmployees.ToList();
            List<Employee> Emp = new List<Employee>();

            foreach (var Rows in result)
            {

                Employee EmpVar = new Employee();
                EmpVar.EmployeeId = Rows.EmployeeId;
                EmpVar.EmployeeName = Rows.EmployeeName;
                EmpVar.FatherName = Rows.FatherName;
                EmpVar.DOB = Convert.ToDateTime(Rows.DOB).ToShortDateString();
                EmpVar.MobileNo =Convert.ToInt16(Rows.MobileNo);
                EmpVar.Age = Convert.ToInt16(Rows.Age);
                EmpVar.EmailId = Rows.EmailId;
                Emp.Add(EmpVar);
            }

            return View(Emp);
        }
  //Add record For Rendering the view or design
        public ActionResult Addrecord()
        {
            ViewBag.Message = "Add Employee Detail";
            return PartialView("Addrecord");
        }
        //Add Record in database
        [HttpPost]
        public ActionResult Addrecord(Employee EmpDetail)
        {
            TblEmployee Emp=new TblEmployee();
            Emp.EmployeeName = EmpDetail.EmployeeName;
            Emp.FatherName = EmpDetail.FatherName;
            Emp.DOB =Convert.ToDateTime(EmpDetail.DOB);
            Emp.MobileNo =EmpDetail.MobileNo;
            Emp.Age = EmpDetail.Age;
            Emp.EmailId = EmpDetail.EmailId;
            Emp.Password = Encrypt(EmpDetail.Password);
            EmpDb.TblEmployees.Add(Emp);
            EmpDb.SaveChanges();
            return RedirectToAction("EmployeeDetails","Employee");
        }
  //Get the Details and display in textbox for Edit
        public ActionResult GetEmployeeDetail(int Id)
        {
            ViewBag.Message = "Edit Employee Detail";
            Employee Emp =new Employee();
            var Result = EmpDb.TblEmployees.Find(Id);
            Emp.EmployeeId = Result.EmployeeId;
            Emp.EmployeeName = Result.EmployeeName;
            Emp.FatherName = Result.FatherName;
            Emp.DOB = Result.DOB.ToString();
            Emp.MobileNo =Convert.ToInt16(Result.MobileNo);
            Emp.Age = Convert.ToInt16(Result.Age);
            Emp.EmailId = Result.EmailId;
            Emp.Password = Decrypt(Result.Password);
            return PartialView("AddRecord", Emp);
        }
//Value will be edit in database
        [HttpPost]
        public ActionResult GetEmployeeDetail(Employee Emp)
        {
            TblEmployee EmpVar = EmpDb.TblEmployees.Where(m => m.EmployeeId == Emp.EmployeeId).FirstOrDefault();
            EmpVar.EmployeeName = Emp.EmployeeName;
            EmpVar.FatherName = Emp.FatherName;
            EmpVar.DOB = Convert.ToDateTime(Emp.DOB);
            EmpVar.MobileNo = Emp.MobileNo;
            EmpVar.Age = Emp.Age;
            EmpVar.EmailId = Emp.EmailId;
            EmpVar.Password = Encrypt(Emp.Password);
            //EmpDb.TblEmployees.Add(EmpVar);
            EmpDb.SaveChanges();
            return RedirectToAction("EmployeeDetails", "Employee");

        }



//For Deleting the record
        [HttpPost]
        public ActionResult DeleteEmployee(int Id)
        {
            TblEmployee Employee = EmpDb.TblEmployees.Where(m => m.EmployeeId == Id).FirstOrDefault();
            EmpDb.TblEmployees.Remove(Employee);
            EmpDb.SaveChanges();
            string Success = "success";
            return Json(Success);
        }
    }
}

step 10 : After Completing the Code of controller create a view for a particular method of control Like Right click on EmployeeDetails and select Add View, so the view generated for EmployeeDetails Method, Most important thing is for particular controller you have to create a particular view

CRUD Operation Modal Popup uses Bootstrap in mvc

CRUD Operation Modal Popup uses Bootstrap in mvc

step 11 : So Your Employeedetail View are is created, So view Part is done, now we have to add and edit in a modal pop up using the bootstrap, first you create a partial view modal pop up, because it is common for both edit and Add record,

Right click on AddRecord in controller and select a partial view from tab

CRUD Operation Modal Popup uses Bootstrap in mvc

step 12 : 

In Partial view let’s write a code for modal pop up for editing and add records

@model MvApp1.Models.Employee


<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>

<div class="modal-dialog" id="ModalPopUp">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title" id="myModalLabel">@ViewBag.Message</h4>
        </div>
        @using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "form-horizontal", @id = "ModalForm" }))
        {
            <div class="modal-body">
                <div class="form-horizontal" style="padding-bottom:5px">

                    @Html.HiddenFor(m => m.EmployeeId)
                    <div class="form-group">
                        @Html.LabelFor(model => model.EmployeeName, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-9">
                            @Html.TextBoxFor(model => model.EmployeeName, new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.EmployeeName, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.FatherName, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-9">
                            @Html.TextBoxFor(model => model.FatherName, "", new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.FatherName, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-9">
                            @Html.TextBoxFor(model => model.DOB, "", new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.MobileNo, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-9">
                            @Html.TextBoxFor(model => model.MobileNo, "", new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.MobileNo, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-9">
                            @Html.TextBoxFor(model => model.Age, "", new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.EmailId, htmlAttributes: new { @class = "control-label col-md-3" })
                        <div class="col-md-9">
                            @Html.TextBoxFor(model => model.EmailId, "", new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.EmailId, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-3" })






            <div class="modal-footer" style="padding:5px">
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <input type="submit" class="btn btn-primary" id="confirmok1" value="Save changes" />
                    </div>
                </div>
            </div>
        }
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        $('.btn-primary').click(function () {
            var std = $(this).attr('id');
            var title = $(this).attr('title');

            //var Id = $(this).attr('id');
            $('#myModal').modal({
                backdrop: 'static',
                keyboard: false
            })
            .on('click', '#confirmok1', function (e) {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Addrecord")',
                    data: '{StudentId: ' + JSON.stringify(std) + '}',
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (response) {
                        window.location.reload();

                        $('#myModal').modal('hide');
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert('oops, something bad happened')
                    }
                });
            });
        });

        });
    });
</script>
Here we complete a code in partial view
Lets Move to EmployeeDetailView
And Write a Code in EmployeeDetailView
@model List<MvApp1.Models.Employee>
@{
    ViewBag.Title = "EmployeeDetails";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/Content/StyleSheet2.css" rel="stylesheet" />
<script>
    $(document).ready(function () {

        $('.btn-bootstrap-dialog').click(function () {
            var url = $(this).data('url');
            var title = $(this).attr('title');

            $.get(url, function (data) {
                $('#bootstrapDialog').html(data);

                $('#bootstrapDialog').modal('show');
               // alert(title)
                $('#ModalPopUp').find('#myModalLabel').html($(this).attr("title"));
            });


        });
        $('.btn-danger').click(function () {
            var std = $(this).attr('id');
            //var Id = $(this).attr('id');
            $('#myModal1').modal({
                backdrop: 'static',
                keyboard: false
            })
            .on('click', '#confirmOk', function (e) {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("DeleteEmployee")',
                        data: '{Id: ' + JSON.stringify(std) + '}',
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: function (success) {
                            window.location.reload();
                            $('#myModal ').modal('hide');
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert('oops, something bad happened')
                        }
                    });
                });
 });
    });
</script>
<div class="container">
    @using (Html.BeginForm(null, null, FormMethod.Post, new { style = "padding-top:65px" }))
    {
@*
        @Html.ActionLink("Create New", "AddRecord", "Employee", null, new {@classs="btn btn-default btn-md", @, @id = "btnCreateAsset" })
        *@<div class="row">
            <div class="col-md-10 col-md-offset-1">
                <div class="panel panel-default panel-table">
                    <div class="panel-heading">
                        <div class="row">
                            <div class="col col-xs-6">
                                <h3 class="panel-title btn">Employee Detail</h3>
                            </div>
                            <div class="col col-xs-6 text-right">
                                <input type="button" class="btn-bootstrap-dialog btn btn-success pull-right" title="Add Employee Detail" data-url="@Url.Action("AddRecord", "Employee", new {title="Add Employee Detail" })" value="Create New" data-toggle="modal" />
                            </div>
                        </div>
                    </div>
                    <div class="panel-body" style="padding-bottom:1px">
                        <table id="TblStudent" class="table table-striped table-bordered table-list">
                            <thead>
                                <tr class="titleTr">
                                    <th class="text-center">Employee Name
                                    </th>
                                    <th class="text-center">Father Name
                                    </th>
                                    <th class="text-center">Date Of Birth
                                    </th>
                                    <th class="text-center">Mobile No
                                    </th>
                                    <th class="text-center">Age
                                    </th>
                                    <th class="text-center">Email Id
                                    </th>
                                    <th class="text-center">Action
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var Data in Model)
                                {
                                    <tr>
                                        <td style="flex-align: center">@Data.EmployeeName</td>
                                        <td style="flex-align: center">@Data.FatherName</td>
                                        <td style="flex-align: center">@Data.DOB</td>
                                        <td style="flex-align: center">@Data.MobileNo</td>
                                        <td style="flex-align: center">@Data.Age</td>
                                        <td style="flex-align: center">@Data.EmailId</td>
                                        <td class="text-center" style="flex-align: center">
                                            <input type="button" class="btn-bootstrap-dialog btn btn-success" value="Edit" data-url="@Url.Action("GetEmployeeDetail", "Employee", new { Id = Data.EmployeeId })"
                                    />
                                            @*@Html.ActionLink("Edit", "Edit", new { @Id = Data.StudentId }) |*@
                                            <input type="button" id="@Data.EmployeeId" class="btn btn-danger" value="Delete" />
                                            @* @Html.ActionLink("Delete", "Delete", new { @Id = Data.StudentId })*@
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
//Its Pop up for Edit and Add
                    <div class="modal fade" id="bootstrapDialog" tabindex="-1" role="dialog" aria-labelledby="myModal-label" aria-hidden="true"></div>

                </div>
            </div>
        </div>
//It’s a pop up for Delete
        <div class="modal fade" id="myModal1" role="dialog">
            <div class="modal-dialog">

                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h5 class="modal-title">Delete Form</h5>
                    </div>
                    <div class="modal-body">
                        <p>are You Sure U want to delete a record?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger pull-right" data-dismiss="modal">Cancel</button>
                        <button type="Submit" class="btn btn-success pull-right" id="confirmOk">Ok</button>

                    </div>
                </div>

            </div>
        </div>

    }
</div>


Here is my Employee Detail view

CRUD Operation Modal Popup uses Bootstrap in mvc

For Create Modal Pop up

CRUD Operation Modal Popup uses Bootstrap in mvc

For Edit Modal Pop up

CRUD Operation Modal Popup uses Bootstrap in mvc

For Delete Pop up

CRUD Operation Modal Popup uses Bootstrap in mvc

Here is my article is completed


Leave Comment

Comments

Liked By