articles

Home / DeveloperSection / Articles / Crud operation(searching, paging) in MVC with modal popup

Crud operation(searching, paging) in MVC with modal popup

Anonymous User 6899 31-Jul-2018

Step 1:

First Create Database in SQL server…

1). Create a Database APCRUD.

2). Create A Table (Customer) into APCRUD database.

Crud operation(searching, paging) in MVC with modal popup

3). Create Stored Procedures for CRUD Operation

Stored Procedure for Insert and Update record

//----------------------Insert and Update Data----------------------//

USE [APCRUD]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[INSERTorUPDATE_CUSTOMER]
@CustomerID INT,
@Name VARCHAR(50),
@Mobileno VARCHAR(20),
@Address VARCHAR(200),
@Birthdate Date = NULL,
@CreationDate DATETIME = NULL,
@EmailID VARCHAR(100)
AS
BEGIN
 IF(@CustomerID=0)
  Begin
   insert into Customer(Name, Mobileno, Address, Birthdate, CreationDate,EmailID) values(@Name, @Mobileno, @Address, @Birthdate, @CreationDate, @EmailID)
   End
  ELSE
   Begin
Update Customer set
Name=@Name,
Mobileno = @Mobileno,
Address = @Address,
Birthdate=@Birthdate,
CreationDate=@CreationDate,
EmailID=@EmailID
where
CustomerID = @CustomerID
End
END
//--------------Stored Procedure for Select All Data---------------//

USE [APCRUD]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[ViewAllRecords_CUSTOMER]
@Name nvarchar(50)
AS
BEGIN
   Select * from Customer WHERE Name LIKE '%'+@Name+'%'
END
//------------Stored procedure for Delete Data by ID-------------------//


USE [APCRUD]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[DeleteRecordByID_CUSTOMER]
@CustomerID int
AS
BEGIN
  Delete from Customer where CustomerID = @CustomerID
END

Step 2 :

Open visual studio ->select file in menu->select New Project on web->select ASP.Net MVC 4 web application-> Select and define the Name of your project->Select an option on project template window like Empty, Basic, Internet, Mobile Application, and

web API ->Choose Empty or Basic.

Crud operation(searching, paging) in MVC with modal popup

Crud operation(searching, paging) in MVC with modal popup

Crud operation(searching, paging) in MVC with modal popup

Step 3.

Create a .edmx file or database model with the help of Entity framework In the visual studio.

Goto solution explorer -> Select project and done right click on it -> Select Add option -> select New item in option list .

Crud operation(searching, paging) in MVC with modal popup

Crud operation(searching, paging) in MVC with modal popup

Crud operation(searching, paging) in MVC with modal popup

Crud operation(searching, paging) in MVC with modal popup

Crud operation(searching, paging) in MVC with modal popup

Step 4 :

Select Controllers folder in solution explorer -> Right click on controllers folder

And Add a controller file with Home name as “HomeController”.

(don't delete ‘Controller’ word from the name of controller file).

Crud operation(searching, paging) in MVC with modal popup

Crud operation(searching, paging) in MVC with modal popup

Step -5 :

After adding the HomeController file. Add an Index file in View folder. Move the cursor in the HomeController file -> And right click under the Action method.

public ActionResult Index()
{
      -----RightClick on Here(for adding a view)----
    return View();
}

Crud operation(searching, paging) in MVC with modal popup

Step 6 :

First Check and Add our system files in HomeController

Like –

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

• Then create an object for our entity framework on header position

Like i.e.

Crud operation(searching, paging) in MVC with modal popup

• Select and explore the model in solution explorer for the only check.

Crud operation(searching, paging) in MVC with modal popup

Step 7: First of all understand some concept of MVC programming before using it.

Like -

1). What is MVC?

2). Why would be used MVC?

3). How MVC is different from ASP.Net.

4). What is Entity Framework and LINQ?

5). SQL Store producer.

6). Naming Convention in programming.

And so on…

Step 8:  Add the new record in the database via the entity framework and modal popup.

(Insert new record via modal popup).

Crud operation(searching, paging) in MVC with modal popup

• Then first create a partial view for _Addrecord action.

Crud operation(searching, paging) in MVC with modal popup

//--------_AddRecord.cshtml----------------//


@model MvcAppFirst.Customer
@{
    ViewBag.Title = "Customer Details";
}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/bootstrap-datepicker.js"></script>
<link href="~/Content/bootstrap-datepicker.css" rel="stylesheet" />
<style>
    #bg {
        background-color: darkgray;
    }
    #DIVBG {
        background-color: Gainsboro;
    }
</style>
@{
    var DOB = "";
    if (Model != null && Model.Birthdate != null)
    {
        DOB = Model.Birthdate.Value.ToString("dd/MM/yyyy");
    }
}
<div class="modal-content" style="width: 800px !important;">
    @using (Ajax.BeginForm(new AjaxOptions() { HttpMethod = "POST", OnSuccess = "onSuccess" }))
    {
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel" align="center">ADD NEW RECORD</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            @Html.ValidationSummary(true)
            <div class="container">
                <div class="col-md-12">
                    <div class="form-area">
                        <br style="clear: both">
                        <div class="form-group">
                            @Html.LabelFor(model => model.Name)
                            @Html.TextBoxFor(model => model.Name, new { @class = "form-control", @placeholder = "Enter Your Full Name" })
                            @Html.ValidationMessageFor(model => model.Name )
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.Mobileno)
                            @Html.TextBoxFor(model => model.Mobileno, new { @class = "form-control", @placeholder = "Enter Your Mobile No.", type = "number"})
                            @Html.ValidationMessageFor(model => model.Mobileno)
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.Birthdate)
                            @Html.TextBoxFor(model => model.Birthdate, new { @class = "form-control datepicker", @Value = @DOB, @placeholder = "Select Your Date Of Birth"})
                            @Html.ValidationMessageFor(model => model.Birthdate)
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.EmailID)
                            @Html.TextBoxFor(model => model.EmailID, new { @class = "form-control", @placeholder = "Enter Your EmailID"})
                            @Html.ValidationMessageFor(model => model.EmailID)
                        </div>
                         <div class="form-group">
                            @Html.LabelFor(model => model.Address)
                            @Html.TextAreaFor(model => model.Address, new { @class = "form-control", @placeholder = "Enter Yor Address"})
                            @Html.ValidationMessageFor(model => model.Address)
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-success">@(Model != null ? "Update" : "Create")</button>
            <button type="button" class="btn btn-warning" onclick="clearTextBox()"><i class="fa fa-search"></i>Reset</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
    }
</div>
<script>
    $(function () {
        $('.datepicker').datepicker({
            format: 'mm/dd/yyyy'
        });
    });
</script>

 . Then create an Action method in the HomeController File.

        [HttpGet]
        public ActionResult Addrecord()
        {
            return PartialView("_AddRecord");
        }
        [HttpPost]
        public ActionResult Addrecord(Customer Cust)
        {
            Cust.CreationDate = DateTime.Now;
            AP.Customers.Add(Cust);
            AP.SaveChanges();
            return RedirectToAction("Index");
        }

• Here( in MVC) before creating a modal popup, we must be read about to

1). What is _Layout.cshtml page in MVC?

2). What is Master Page in Asp.Net?

3). What is similar to MasterPage and Layout page?

Layout Page in mvc -

When we want to a common layout or effects on overall our application then we used the _Layout.cshtml page in MVC for design and scripting.

Crud operation(searching, paging) in MVC with modal popup

//-----------_Layout Page for common Display-----//

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/Content/main.css" rel="stylesheet" />
    <link href="~/Content/PagedList.css" rel="stylesheet" />
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/themes/base/datepicker.css" rel="stylesheet" />
</head>
<body>
    <div style="padding: 0px 55px;">
        @RenderBody()
    </div>
        <div class="modal fade" id="modal-dialog" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" >
            <div id="modalContent" >
            </div>
        </div>
    </div>
    <div class="modal fade" id="message-dialog" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div id="messageContent">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title centerAlign" >Confirmation</h4>
                    </div>
                    <div class="modal-body">
                        Are you sure you want to delete?
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger" id="confirmOk">OK</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="~/Content/jquery.js"></script>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="~/Content/bootstrap.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/main.js"></script>
</body>
</html>

• Create your self-scripting page as a .js file on the RightClick on script folder in solution explorer.

Crud operation(searching, paging) in MVC with modal popup

//------For retrive the Record into the modalpopup for edit and update------//

$(document).ready(function () {
    $(".open-dialog").click(function (e) {
        e.preventDefault();
        console.log(this.getAttribute('href'));
        $.ajax({
            url: this.getAttribute('href'),
            data: {},
            type: 'GET',
            success: function (data) {
                //alert(data);
                $('#modalContent').html(data);
                $('#modal-dialog').modal('show');
            }
        });
    });
})

. For clear all text field, click on the Reset button.

//------Function for clearing the textboxes------//

function clearTextBox() {
    $('#Name').val("");
    $('#Address').val("");
    $('#Mobileno').val("");
    $('#Birthdate').val("");
    $('#EmailID').val("");
    $('#Name').css('border-color', 'lightgrey');
    $('#Address').css('border-color', 'lightgrey');
    $('#Mobileno').css('border-color', 'lightgrey');
    $('#EmailID').css('border-color', 'lightgrey');
}

After creating a main.js file then create a .css file in CSS folder.

Crud operation(searching, paging) in MVC with modal popup

Note : when we define CSS property in .css file there are no need to define "<style></style>" tags.

    .centerAlign {
        text-align: center;
    }
    table#customerDetails {
        width: 100%;
        background-color: #f1f1c1;
    }
        table#customerDetails tr:nth-child(even) {
            background-color: #eee;
        }
        table#customerDetails tr:nth-child(odd) {
            background-color: #fff;
        }
        table#customerDetails th {
            color: white;
            background-color: DarkGray;
        }
    table, th, td {
        border: 1px solid black;
    }
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
    th, td {
        padding: 15px;
    }
    body {
        font-family: Arial;
    }
    * {
        box-sizing: border-box;
    }
    .rightAlign {
        text-align: right;
    }
    .headerPadding {
        padding: 5px;
    }
    .modal-content {
        width: 500px !important;
        margin: 30px auto !important;
    }
     .red {
        color: red;
    }
    .form-area {
        background-color: #FAFAFA;
        padding: 10px 40px 60px;
        margin: 10px 0px 60px;
        border: 1px solid GREY;
    }

Edit, Inserted Record: First, fill the record in modal popup fields by the click on Edit button.

Here we have already defined the script code for filling the entire fields into the modal popup on above position. And here defined only Action method for Edit and Update data.

//-------Edit and Update record By using the stored procedure------// //-----Use ajax script for Get record---(script has defined on page above side)----//

[HttpGet]
        public ActionResult EditStudent(int customerID)
        {
            var model=AP.Customers.FirstOrDefault(x => x.CustomerID == customerID);
            return PartialView("_AddRecord", model);
        }
        [HttpPost]
        public ActionResult EditStudent(Customer Cust)
        {
            bool success = false;
            var Customer = AP.Customers.Where(x => x.CustomerID == Cust.CustomerID).FirstOrDefault();
            if (Customer != null)
            {
                success = AP.INSERTorUPDATE_CUSTOMER(Cust.CustomerID, Cust.Name, Cust.Mobileno, Cust.Address, Cust.Birthdate, DateTime.Now, Cust.EmailID) == 1 ? true : false;
                AP.SaveChanges();
            }
            return RedirectToAction("Index");
        }

Delete Record with Confirmation Dialog popup.

Crud operation(searching, paging) in MVC with modal popup

//------Delete Action Method-------//

public ActionResult DeleteCustomer(int customerID)
        {
            bool success = false;
            success = AP.DeleteRecordByID_CUSTOMER(customerID) == 1 ? true : false;
            AP.SaveChanges();
            return RedirectToAction("Index");
        }

This script code is used For Delete Confirmation popup.

//------For Confirmation Dilogbox on delete button click------//

$(".delete-dialog").click(function (e) {
    e.preventDefault();
    var deleteLinkObject = $(this);
    $('#message-dialog').modal('show');
    $("#confirmOk").click(function (e) {
        $.ajax({
            cache: false,
            async: true,
            type: "GET",
            url: deleteLinkObject.attr("href"),
            success: function () {
                $('#delete-dialog').modal('hide');
                location.reload();
            }
        });
    });
});

Index File Coding for the view.

//-------- Index Page View---------//

@model PagedList.IPagedList<MvcAppFirst.ViewAllRecords_CUSTOMER_Result>
@using PagedList.Mvc;
@using PagedList;
@{
    ViewBag.Title = "Customer Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 align="center"><u>Customer Details</u></h2>
@using (Html.BeginForm())
{
    <div>
        <div class="row">
            <div class="col-md-6">
                <button class="btn btn-primary open-dialog rightAlign" href="@Url.Action("Addrecord", "Home")">
                    Add New User
                </button>
            </div>
            <div class="col-md-6 rightAlign form-group">
                <form method="get">
                    <input type="text" placeholder="Search.." name="searchText">
                    <button type="submit" class="btn btn-info"><i class="fa fa-search"></i>Search</button>
                </form>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <table id="customerDetails">
                    <thead class="centerAlign">
                        <tr>
                            <th>CustomerID</th>
                            <th>CustomerName</th>
                            <th>Address</th>
                            <th>MobileNo</th>
                            <th>BirthDate</th>
                            <th>EmailID</th>
                            <th>CreationDate</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>@item.CustomerID </td>
                            <td>@item.Name </td>
                            <td>@item.Address </td>
                            <td>@item.Mobileno </td>
                            <td>@item.Birthdate.Value.ToString("dd/MM/yyyy") </td>
                            <td>@item.EmailID </td>
                            <td>@item.CreationDate</td>
                            <td class="text-center" style="flex-align: center">
                                <a href="@Url.Action("EditStudent", "Home", new { customerID = @item.CustomerID })" class="btn btn-info open-dialog">Edit</a>
                                <a href="@Url.Action("DeleteCustomer", "Home", new { customerID = @item.CustomerID })" class="btn btn-danger delete-dialog" onclick="return onDelete();">Delete</a>
                            </td>
                        </tr>
                    }
                </table>
                <div class="col-md-12">
                    <div id='Paging' style="text-align: center">
                        Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
                        of @Model.PageCount
                        @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
                    </div>
                </div>
            </div>
        </div>
    </div>
}     



Updated 03-Sep-2020
I am a content writter !

Leave Comment

Comments

Liked By