articles

Home / DeveloperSection / Articles / Insert update delete in mvc via webgrid and modal popup

Insert update delete in mvc via webgrid and modal popup

Anonymous User6854 04-Jan-2019

Hi friends,

Today I'm going to describe the use of Webgrid in asp.net MVC. If you have used Gridview control in ASP.NET, it will be easy for you. So let's start it...

Insert update delete in mvc via webgrid and modal popup

Step (1)- You create a database and a data table in SQL.

Insert update delete in mvc via webgrid and modal popup

Step(2) - You will create a new MVC project in visual studio.

Insert update delete in mvc via webgrid and modal popup

Step(3) - Add entity framework by NuGet Package if not installed already. 

Insert update delete in mvc via webgrid and modal popup

Insert update delete in mvc via webgrid and modal popup

Step(4) - Add Repository.cs and IRepository.cs files in model folder.

Insert update delete in mvc via webgrid and modal popup

Repository.cs

using System;

using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace MvcApplication5.Models.DAL
{
    public class BookRepository
    {
        private DBContext _context;

        public BookRepository(DBContext context)
        {
            _context = context;
        }

        public IEnumerable<BookTbl> GetBooks()
        {
            return _context.BookTbls.ToList();
        }

        public BookTbl GetBookByID(int bookId)
        {
            return _context.BookTbls.Find(bookId);
        }

        public void InsertBook(BookTbl book)
        {
            _context.BookTbls.Add(book);
        }

        public void DeleteBook(int bookId)
        {
            BookTbl book = _context.BookTbls.Find(bookId);
            _context.BookTbls.Remove(book);
        }

        public void UpdateBook(BookTbl book)
        {
            _context.Entry(book).State = EntityState.Modified;
        }

        public void Save()
        {
            _context.SaveChanges();
        }
    }
}

IRepository.cs

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MvcApplication5.Models.DAL
{
    interface IBookRepository
    {
        IEnumerable<BookTbl> GetBooks();
        BookTbl GetBookByID(int bookId);
        void InsertBook(BookTbl book);
        void DeleteBook(int bookId);
        void UpdateBook(BookTbl book);
        void Save();
    }
}

Step(5) - Add HomeController.cs file in controller folder

HomeController.cs

using MvcApplication5.Models;

using MvcApplication5.Models.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication5.Controllers
{
    public class HomeController : Controller
    {
        private BookRepository interfaceobj;

        public HomeController()
        {
            interfaceobj = new BookRepository(new DBContext());
        }

        public ActionResult Index()
        {
            //var test = interfaceobj.GetBooks();
            //var data = from m in interfaceobj.GetBooks() select m;
            return View(interfaceobj.GetBooks());
        }

        public ActionResult Create()
        {
            return PartialView("_AddRecord");
        }
        [HttpPost]
        public ActionResult Create(BookTbl book)
        {
            interfaceobj.InsertBook(book);
            interfaceobj.Save();
            return RedirectToAction("Index");
        }

        public ActionResult Details(int id)
        {
            BookTbl dtlObj = interfaceobj.GetBookByID(id);
            return View("_DetailPage",dtlObj);
        }

        public ActionResult Delete(int id)
        {
            interfaceobj.DeleteBook(id);
            interfaceobj.Save();
            return RedirectToAction("Index");
        }

        public ActionResult Edit(int id)
        {
            BookTbl model = interfaceobj.GetBookByID(id);
            return PartialView("_AddRecord", model);
        }

        [HttpPost]
        public ActionResult Edit(BookTbl book)
        {
            interfaceobj.UpdateBook(book);
            interfaceobj.Save();
            return RedirectToAction("Index");
        }
    }
}

Step(5) - Add _LayoutPage.cshtml for common UI like modal popup.

<html>

<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @* <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />*@
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href="~/Content/second.css" rel="stylesheet" />
    <link href="~/Content/PagedList.css" rel="stylesheet" />
</head>
<body>

    <div style="padding: 0px 55px;">
        @RenderBody()
    </div>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modal-title">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="modal-content"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                   @* <button type="button" class="btn btn-primary">Save changes</button>*@
                </div>
            </div>
        </div>
    </div>

    <!--Confirmation-->

    <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="~/Scripts/bootstrap.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/main.js"></script>
</body>
</html>


Step(6) - Add a view file in view folder with "Index.cshtml" and webgrid controll

Index.cshtml

@model IEnumerable<MvcApplication5.Models.BookTbl>


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";
}


<div id="DivGrid" class="container">

    @*<button class="btn btn-primary btn-md" id="btnmodal-dialog" href="@Url.Action("Create", "Home")"> Insert New Record </button>*@
    <button class="btn btn-primary btn-md modal-Dialog-AddUpdate" exthref="@Url.Action("Create", "Home")" id="btnmodal-dialog">Insert New Record </button>

    @{
        var grid = new WebGrid(source: Model);
        @grid.GetHtml(tableStyle: "PGrid", headerStyle: "Header", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
        grid.Column("ID"),
        grid.Column("BookName"),
        grid.Column("BookAuthor"),
        grid.Column("", header: "Action", format: @<text>

        <a href="#" exthref="@Url.Action("Edit", "Home", new { id = @item.id })" class="modal-Dialog-AddUpdate">Edit</a>&nbsp;

                    <a href="#" exthref="@Url.Action("Delete", "Home", new { id = @item.id })" class="delete-dialog">Delete</a>&nbsp;

                                <a href="#" exthref="@Url.Action("Details", "Home", new { id = @item.id })" class="modal-Dialog-AddUpdate">Detail</a>&nbsp;

                                                  </text>)));
    }

</div>


@*@Html.ActionLink("Edit", "Edit", "Id", new { id = item.Id }, new { target = "_blank", @class = "modal-Dialog-AddUpdate" })*@

Step(7) - Add seperet _PartialView for differenet methods Like - Edit, Details etc.

 Insert update delete in mvc via webgrid and modal popup

First - ADD and Edit record

@model MvcApplication5.Models.BookTbl


@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm())
{
    if (Model != null)
    {
    @Html.HiddenFor(x => x.ID)
    }

    <div class="row">
        <div class="col-md-12">
           <h6> <label class="control-label">Book Name</label></h6>
        </div>
        <div class="col-md-12">
            @Html.TextBoxFor(x => x.BookName, new { @class = "form-control" })
            @*<input class="form-control" name="BookName" type="text" id="txtBookName" />*@
        </div>
        <div class="col-md-12">
            <h6><label class="control-label">Book Author</label></h6>
        </div>
        <div class="col-md-12">
            @Html.TextBoxFor(x => x.BookAuthor, new { @class = "form-control" })
            @*<input class="form-control" name="BookAuthor" type="text" id="txtBookAuthor" />*@
        </div>
        <div class="col-md-12" style="margin-top: 20px">
            <div class="row">
                <div class="col-md-2">
                    <button class="btn btn-primary" type="submit">@(Model != null ? "Update" : "Add")
                    </button>
                    @*<input class="btn btn-primary" type="submit" id="btnSave" value="Save" />*@
                </div>
                @* <div class="col-md-10">
                    @Html.ActionLink("Back to List", "Index")
                </div>*@
            </div>
        </div>
    </div>
}

Second - Details of record

@model MvcApplication5.Models.BookTbl



<div class="modal-body">
    <div class="form-horizontal">
        <div class="form-group">
         <h5>@Html.LabelFor(m => Model.BookName, new { @class = "control-label col-sm-3" })</h5>
            <div class="col-sm-9">
                @Html.TextBoxFor(m => m.BookName, new { @class = "form-control required", @disabled = "disabled" })
            </div>
        </div>

        <div class="form-group">
           <h5>@Html.LabelFor(m => Model.BookAuthor, new { @class = "control-label col-sm-3" })</h5>
            <div class="col-sm-9">
                @Html.TextBoxFor(m => m.BookAuthor, new { @class = "form-control required", @disabled = "disabled" })
            </div>
        </div>
    </div>
</div>

Third - Delete action will be performed by modal popup. Which is contained in the _LayoutPage.cshtml.

Step(8) - All script is collecting in a single file main.js

$(document).ready(function () {

    $(".modal-Dialog-AddUpdate").click(function () {
        var elem = $(this);
        var href = elem.attr('exthref');
        $.ajax({
            url: href,
            type: 'Get',
            success: function (data) {
                $('#modal-title').html('Add Record');
                $('#modal-content').html(data);
                $('#myModal').modal('show');
            }
        });
    });
});

$(".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("exthref"),
            success: function () {
                $('#delete-dialog').modal('hide');
                location.reload();
            }
        });
    });
});

$(document).ready(function () {
    $(".modal-Dialog-AddUpdate").click(function () {
        var elem = $(this);
        var href = elem.attr('exthref');
        $.ajax({
            url: href,
            type: 'Get',
            success: function (data) {
                $('#modal-title').html('Record Detail');
                $('#modal-content').html(data);
                $('#myModal').modal('show');
            }
        });
    });
});




//$(document).ready(function () {
// $(".open-dialog").click(function (e) {
// alert();
// //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');
// // }
// //});
// });
//})

 Step(9) - All CSS are collecting in main.css file

    .centerAlign {

        text-align: center;
    }

    .table {
        padding:150px;
        width: 100%;
        background-color: #f1f1c1;
    }

        table tr:nth-child(even) {
            background-color: #eee;
        }

        table tr:nth-child(odd) {
            background-color: #fff;
        }

        table 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;
    }
    .center {
  margin: 300px;
  width:auto;
  border: 1px solid #73AD21;
  padding: 10px;
}
 .button {
        background-color: #4CAF50; /* Green */
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
    }

    .button1 {
        border-radius: 2px;
    }

    .button2 {
        border-radius: 4px;
    }

    .button3 {
        border-radius: 8px;
    }

    .button4 {
        border-radius: 12px;
    }

    .button5 {
        border-radius: 50%;
    }

   .tr-color-selected{
background-color: hsla(196, 77%, 55%, 0.3) !important;
transition: all .2s ease-in;
}

And Final Result is our project is - 

For Add record

Insert update delete in mvc via webgrid and modal popup

For Edit/Update Record

Insert update delete in mvc via webgrid and modal popup

For Detail record

Insert update delete in mvc via webgrid and modal popup

For Delete record

Insert update delete in mvc via webgrid and modal popup

And So On.....

End of this project.

Thanks for reading this article..!!! If any suggestion please comment me.

And yes, if you want to read more about MVC, then follow the link below.

https://www.mindstick.com/articles/13124/generic-repository-pattern-in-c-sharp

https://www.mindstick.com/articles/13108/crud-operation-in-mvc-with-repository-pattern


Updated 25-Apr-2020
I am a content writter !

Leave Comment

Comments

Liked By