Subscribe Us

LightBlog

Tuesday, 30 June 2020

June 30, 2020

Display Colorized Rows Of WebGrid In ASP.NET MVC

script type="text/javascript">
    $(document).ready(function()  
       {  
  
        $('#gridMapping > tbody > tr').each(function(index)  
            {  
  
            if ($(this).children('td:nth-child(5)').text() == "Done")  
            {  
                $(this).children('td').css("background-color", "#33CC99");  
            } else   
            {  
                $(this).children('td').css("background-color", "#FFCC99");  
            }  
  
        });  
    });  
</script>


Sunday, 28 June 2020

June 28, 2020

Asp.Net MVC CRUD Operations Using Datatable

Table Script

CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Position] [varchar](50) NULL,
[Office] [varchar](50) NULL,
[Age] [int] NULL,
[Salary] [int] NULL,
)

Command to update MVC old versions to MVC 5.1 ➤ Install-Package Microsoft.AspNet.MVC -Version 5.1.0
implementing crud operation using ADO.NET Entity Model.

Employee Controller

-Create Empty controller.
public ActionResult Index() { return View(); } public ActionResult GetData() { using (MvcCRUDDBEntities db = new MvcCRUDDBEntities()) { List<Employee> empList = db.Employees.ToList<Employee>(); return Json(new { data = empList }, JsonRequestBehavior.AllowGet); } } [HttpGet] public ActionResult AddOrEdit(int id = 0) { if (id == 0) return View(new Employee()); else { using (MvcCRUDDBEntities db = new MvcCRUDDBEntities()) { return View(db.Employees.Where(x => x.EmployeeID==id).FirstOrDefault<Employee>()); } } } [HttpPost] public ActionResult AddOrEdit(Employee emp) { using (MvcCRUDDBEntities db = new MvcCRUDDBEntities()) { if (emp.EmployeeID == 0) { db.Employees.Add(emp); db.SaveChanges(); return Json(new { success = true, message = "Record Saved Successfully" }, JsonRequestBehavior.AllowGet); } else { db.Entry(emp).State = EntityState.Modified; db.SaveChanges(); return Json(new { success = true, message = "Record Updated Successfully" }, JsonRequestBehavior.AllowGet); } } } [HttpPost] public ActionResult Delete(int id) { using (MvcCRUDDBEntities db = new MvcCRUDDBEntities()) { Employee emp = db.Employees.Where(x => x.EmployeeID == id).FirstOrDefault<Employee>(); db.Employees.Remove(emp); db.SaveChanges(); return Json(new { success = true, message = "Record Deleted Successfully" }, JsonRequestBehavior.AllowGet); } } }

-Add view for method Index and AddOrEdit
-add Bootstrap and jQuery UI nuGet Package

Index.cshtml

@{
    ViewBag.Title = "Employee List";
}

<h2>Employee CRUD Operations</h2>

<a class="btn btn-success" style="margin-bottom:10px" onclick="PopupForm('@Url.Action("AddOrEdit","Employee")')"><i class="fa fa-plus"></i> Add New</a>
<table id="employeeTable" class="table table-striped table-bordered" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
            <th></th>
        </tr>
    </thead>
</table>

<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

@section scripts{
    <script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>

    <script>
        var Popup, dataTable;
        $(document).ready(function () {
            dataTable =  $("#employeeTable").DataTable({
                "ajax": {
                    "url": "/Employee/GetData",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns": [
                    { "data": "Name" },
                    { "data": "Position" },
                    { "data": "Office" },
                    { "data": "Age" },
                    { "data": "Salary" },
                    {"data":"EmployeeID" , "render" : function (data) {
                        return "<a class='btn btn-default btn-sm' onclick=PopupForm('@Url.Action("AddOrEdit","Employee")/" + data + "')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete("+data+")><i class='fa fa-trash'></i> Delete</a>";
                    },
                        "orderable": false,
                        "searchable":false,
                        "width":"150px"
                    }

                ],
                "language": {

                    "emptyTable" : "No data found, Please click on <b>Add New</b> Button"
                }
            });
        });

        function PopupForm(url) {
            var formDiv = $('<div/>');
            $.get(url)
            .done(function (response) {
                formDiv.html(response);

                Popup = formDiv.dialog({
                    autoOpen: true,
                    resizable: false,
                    title: 'Fill Employee Details',
                    height: 500,
                    width: 700,
                    close: function () {
                        Popup.dialog('destroy').remove();
                    }

                });
            });
        }

        function SubmitForm(form) {
            $.validator.unobtrusive.parse(form);
            if($(form).valid()){
                $.ajax({
                    type : "POST",
                    url : form.action,
                    data : $(form).serialize(),
                    success : function (data) {
                        if(data.success)
                        {
                            Popup.dialog('close');
                            dataTable.ajax.reload();

                            $.notify(data.message,{
                                globalPosition :"top center",
                                className : "success"
                            })

                        }
                    }
                });
            }
            return false;
        }

        function Delete(id) {
            if(confirm('Are You Sure to Delete this Employee Record ?'))
            {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Delete","Employee")/' + id,
                    success: function (data) {
                        if (data.success)
                        {
                            dataTable.ajax.reload();

                            $.notify(data.message, {
                                globalPosition: "top center",
                                className: "success"
                            })

                        }
                    }

                });
            }
        }
    </script>
}

AddOrEdit.cshtml

@model Asp.NETMVCCRUD.Models.Employee @{ Layout = null; } @using (Html.BeginForm("AddOrEdit", "Employee", FormMethod.Post, new {onsubmit = "return SubmitForm(this)" })) { @Html.HiddenFor(model => model.EmployeeID) <div class="form-group"> @Html.LabelFor(model => model.Name, new { @class = "control-label" }) @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Name) </div> <div class="form-group"> @Html.LabelFor(model => model.Position, new { @class = "control-label" }) @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Position) </div> <div class="form-group"> @Html.LabelFor(model => model.Office, new { @class = "control-label" }) @Html.EditorFor(model => model.Office, new { htmlAttributes = new { @class = "form-control" } }) </div> <div class="form-group"> @Html.LabelFor(model => model.Age, new { @class = "control-label" }) @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } }) </div> <div class="form-group"> @Html.LabelFor(model => model.Salary, new { @class = "control-label" }) <div class="input-group"> <span class="input-group-addon">$</span> @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } }) </div> </div> <div class="form-group"> <input type="submit" value="Submit" class="btn btn-primary" /> <input type="reset" value="Reset" class="btn" /> </div> }

Monday, 8 June 2020

June 08, 2020

How to save data from Html controls in your local storage when page is load

Index.html

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <title></title>
   </head>
   <script type="text/javascript"></script>
   <body>
      <center>
         From Date:<br>
         <input type="date" id="datefrom" name="datefrom" class="auto-save">
         <br>
         To Date:<br>
         <input type="date" id="to" name="dateto" class="auto-save">
         <br>
      </center>
      <br><br><br><br>
      <button type="button" name="button" onclick="dstry()">Destroy all data</button>
   </body>
</html>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh" crossorigin="anonymous"></script>
<script type="text/javascript" src="savy.js"></script>
<script type="text/javascript">
   $('.auto-save').savy('load',function(){
     console.log("All data from savy are loaded");
   });
   
   function dstry(){
     $('.auto-save').savy('destroy',function(){
       console.log("All data from savy are Destroyed");
       window.location.reload();
     });
   }
</script>

savy.js

(function($) {
  $.fn.savy = function(order,fn) {
    const sv = "savy-";
    if (order == "load") {
      $(this).each(function() {
        if ($(this).is(":radio")) {
          if(localStorage.getItem(sv+$(this).attr("name"))){
            if (localStorage.getItem(sv+$(this).attr("name")) == this.id) {
              this.checked = true;
            }else{
              this.checked = false
            }
          }
          $(this).change(function() {
            localStorage.setItem(sv+$(this).attr("name"), this.id);
          });
        }else if($(this).is(":checkbox")){
          if(localStorage.getItem(sv+this.id)){
            this.checked = (localStorage.getItem(sv+this.id) == "1" ? true : false);
          }
          $(this).change(function() {
            localStorage.setItem(sv+this.id, (this.checked ? "1" : "0"));
          });
        }else if($(this).is("input") || $(this).is("textarea")) {
          if(localStorage.getItem(sv+this.id)){
            this.value = localStorage.getItem(sv+this.id);
          }
          $(this).keyup(function() {
            localStorage.setItem(sv+this.id, this.value);
          });
        }else if($(this).is("select")) {
          if ($(this).is("[multiple]")) {
            if(localStorage.getItem(sv+this.id)){
              $(this).val(localStorage.getItem(sv+this.id).split(","));
            }else{
              localStorage.setItem(sv+this.id, $(this).val());
            }
            $(this).change(function() {
              localStorage.setItem(sv+this.id, $(this).val());
            });
          }else{
            if(localStorage.getItem(sv+this.id)){
              $(this).val(localStorage.getItem("savy-"+this.id));
            }else{
              localStorage.setItem(sv+this.id, $(this).val());
            }
            $(this).change(function() {
              localStorage.setItem(sv+this.id, $(this).val());
            });
          }

        }
      });
      if ($.isFunction(fn)){fn();}
    }else if (order == "destroy") {
      $(this).each(function() {
        if(localStorage.getItem(sv+this.id)){
          localStorage.removeItem(sv+this.id)
        }
      });
      if ($.isFunction(fn)){fn();}
    }else{
      console.error("savy action not defined please use $('.classname').savy('load') to trigger savy to save all inputs")
    }
  };
})(jQuery);


No image