Wednesday, 4 March 2015

MVC Editable Grid

Employee Helper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCEditableGrid;
using MVCEditableGrid.Viewmodels;
using MVCEditableGrid.Models;
using System.Web.Mvc;
using System.Data;

namespace MVCEditableGrid.helpers
{
    public class EmployeeHelper : IDisposable
    {
        EmployeeEntities _dbconn = new EmployeeEntities();

        public List<EmlpyeesViewmodel> GetEmployees()
        {
            List<EmlpyeesViewmodel> EmployeeList = new List<EmlpyeesViewmodel>();
            EmployeeList = (from e in _dbconn.EmployeeMasters
                            join d in _dbconn.Departments on e.DeptId equals d.DeptId
                            select new EmlpyeesViewmodel
                            {
                                EmployeeId = e.EmployeeId,
                                EmployeeName = e.EmployeeName,
                                PhoneNumber = e.PhoneNumber,
                                DeptName = d.DeptName,
                                DeptId = d.DeptId
                            }).ToList();

            return EmployeeList;
        }

        public IEnumerable<SelectListItem> GetDepartment(int dept_Id)
        {
            List<SelectListItem> DepartmentList = new List<SelectListItem>();
            var department = _dbconn.Departments.ToList();
            department.ForEach(d => DepartmentList.Add(new SelectListItem() { Text = d.DeptName,Value = d.DeptId.ToString(),Selected = dept_Id == d.DeptId }));
            return DepartmentList;
        }

        public string Save(EmployeeMaster model)
        {
            if (model == null)
                return "Fail to update";
            else
            {
                try
                {
                    EmployeeMaster employee = _dbconn.EmployeeMasters.Where(e => e.EmployeeId == model.EmployeeId).SingleOrDefault();
                    _dbconn.Entry(employee).State = EntityState.Modified;
                    employee.EmployeeName = model.EmployeeName;
                    employee.PhoneNumber = model.PhoneNumber;
                    employee.DeptId = model.DeptId;
                    _dbconn.SaveChanges();
                    return "Success";
                }
                catch
                {
                    return "Fail to update";
                }
            }
         
        }

        #region IDisposable
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {

            if (disposing)
            {
                if (_dbconn != null) _dbconn.Dispose();
                _dbconn = null;
            }

        }
        #endregion
    }

}

EmployeeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCEditableGrid.helpers;
using MVCEditableGrid.Viewmodels;

namespace MVCEditableGrid.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult EmployeeList()
        {
            return View();
        }


        public ActionResult GridView()
        {
            using (EmployeeHelper helper = new EmployeeHelper())
            {
                List<EmlpyeesViewmodel> EmployeeList = new List<EmlpyeesViewmodel>();
                EmployeeList = helper.GetEmployees();
                foreach (EmlpyeesViewmodel value in EmployeeList)
                {
                    value.Department = helper.GetDepartment(value.DeptId);

                }
                return View("GridView",EmployeeList);
            }
        }

        [HttpPost]
        public JsonResult save(EmployeeMaster model)
        {
            string message;
            using (EmployeeHelper helper = new EmployeeHelper())
            {
                message = helper.Save(model);
            }
            return Json(message, JsonRequestBehavior.AllowGet);

        }
    }

}

EmployeeList.cshtml
@*@model IEnumerable<MVCEditableGrid.Viewmodels.EmlpyeesViewmodel>*@
@{
    ViewBag.Title = "EmployeeList";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>EmployeeList</h2>
<div id="divgrid">
     @Html.Action("GridView")
</div>

GridView.cshtml
@model IEnumerable<MVCEditableGrid.Viewmodels.EmlpyeesViewmodel>
@{
    Layout = null;
}
<table>
    @foreach (var group in Model.GroupBy(x => x.DeptName))
    {
        <tr class="group-header" style="border-bottom: 1px solid">
            <td colspan="6">
                <span class="h3">@group.Key</span>
            </td>
        </tr>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EmployeeName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PhoneNumber)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.DeptName)
            </th>
            <th></th>
        </tr>
        foreach (var item in group)
        {
        <tr>
            <td>
                <div>
                    @Html.TextBoxFor(modelItem => item.EmployeeName, new { id = "txtEmployeeName", @class = "display-mode", @style = "display: none" })
                </div>
                @Html.Label(item.EmployeeName, new { id = "lblEmployeeName", @class = "edit-mode" })
            </td>
            <td>
                <div>
                    @Html.TextBoxFor(modelItem => item.PhoneNumber, new { id = "txtPhoneNumber", @class = "display-mode", @style = "display: none" })
                </div>
                @Html.Label(item.PhoneNumber, new { id = "lblPhoneNumber", @class = "edit-mode" })
            </td>
            <td>
                <div>
                    @Html.DropDownList("Department", item.Department, "", new { id = "DepartmentId", @class = "display-mode", @style = "display: none" })
                </div>
                @Html.HiddenFor(modelItem => item.DeptId, new { id = "hdnDeptId" })
                @Html.Label(item.DeptName, new { id = "lblDepartment", @class = "edit-mode" })
            </td>
            <td>
                @Html.HiddenFor(modelItem => item.EmployeeId, new { id = "hdnEmpId" })
                <a href="#" class="Editlink" onclick="Edit(this);" style="display: block">Edit</a>
                <a href="#" class="Savelink" onclick="Save(this);" style="display: none">Save</a>
                <a href="#" class="Cancellink" onclick="Cancel(this);" style="display: none">Cancel</a>
            </td>
        </tr>
        }
    }
</table>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script>
    function Edit(tag) {
        $(tag).siblings('a').show();
        $(tag).hide();
        var tr = $(tag).parents('tr');
        $('.display-mode').hide(); /// to show one editable row at a time
        $('.edit-mode').show();

        tr.find('.edit-mode').hide();
        tr.find('.display-mode').show();
    }

    function Cancel(tag) {
        var tr = $(tag).parents('tr');
        tr.find('#txtEmployeeName').val(tr.find('#lblEmployeeName').text());
        tr.find('#txtPhoneNumber').val(tr.find('#lblPhoneNumber').text());
        tr.find('#DepartmentId').val(tr.find('#hdnDeptId').val());
        tr.find('.edit-mode').show();
        tr.find('.display-mode').hide();
        $(tag).siblings('a.Editlink').show();
        $(tag).siblings('a.Savelink').hide();
        $(tag).hide();
    }

    function Save(tag) {
        var tr = $(tag).parents('tr');
        tr.find('#lblEmployeeName').text(tr.find('#txtEmployeeName').val());
        tr.find('#lblPhoneNumber').text(tr.find('#txtPhoneNumber').val());
        tr.find('#lblDepartment').text(tr.find('#DepartmentId :selected').text());
        tr.find('#hdnDeptId').val(tr.find('#DepartmentId').val());
        tr.find('.edit-mode').show();
        tr.find('.display-mode').hide();
        $(tag).siblings('a.Editlink').show();
        $(tag).siblings('a.Cancellink').hide();
        $(tag).hide();

        var EmployeeId = tr.find("#hdnEmpId").val();
        var EmployeeName = tr.find("#lblEmployeeName").text();
        var PhoneNumber = tr.find("#lblPhoneNumber").text();
        var DeptId = tr.find("#hdnDeptId").val();

        var Model =
           {
               "EmployeeId": EmployeeId,
               "EmployeeName": EmployeeName,
               "PhoneNumber": PhoneNumber,
               "DeptId": DeptId
           };
        console.log(Model);
        $.ajax({
            url: '/Employee/save/',
            data: JSON.stringify(Model),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                alert(data);
                Refreshgrid();
            }
        });
    }

    function Refreshgrid() {
        $.ajax({
            url: '/Employee/GridView/',
            type: 'POST',
            dataType: 'html',
            //contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $("#divgrid").html(data);
            }
        });
    }
</script>

2 comments: