Monday, March 12, 2018

MVC Demo With Grid Paging,Sorting,Serching

===============================
Home Controller - Controller
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UniqDataMvc.DataService;
using UniqDataMvc.Models;

namespace UniqDataMvc.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetEmployees()
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                //dalc dc = new dalc();
                //var employees = dc.EmployeeMasters.OrderBy(a => a.Name).ToList();
                //return Json(new { data = employees }, JsonRequestBehavior.AllowGet);

                List<EmployeeMaster> emp = new dalc().selectbyquerydt("select E.*,D.DepName As DepartmentName from EmployeeMaster as E inner join departmentMaster as D on D.DepId=E.depId").ConvertToList<EmployeeMaster>().ToList();
                return Json(new { data = emp }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpGet]
        public ActionResult Save(int id)
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                var v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                ViewBag.deptList = dc.departmentMasters.ToList();
                return View(v);
            }
        }

        public ActionResult Save(EmployeeMaster emp)
        {
            bool status = false;
            if (ModelState.IsValid)
            {
                using (VensystemMvcEntities dc = new VensystemMvcEntities())
                {
                    if (emp.EmpId > 0)
                    {
                        //Edit
                        var v = dc.EmployeeMasters.Where(a => a.EmpId == emp.EmpId).FirstOrDefault();
                        if (v != null)
                        {
                            v.Name = emp.Name;
                            v.Email = emp.Email;
                            v.MobileNo = emp.MobileNo;
                            v.depId = emp.depId;
                            v.Birthdate = emp.Birthdate;
                        }
                    }
                    else
                    {
                        //Save
                        dc.EmployeeMasters.Add(emp);
                    }
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
        }

        [HttpGet]
        public ActionResult Delete(int id)
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                EmployeeMaster v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                if (v != null)
                {
                    return View(v);
                }
                else
                {
                    return HttpNotFound();
                }
            }
        }

        [HttpPost]
        [ActionName("Delete")]
        public ActionResult DeleteEmployee(int id)
        {
            bool status = false;
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                var v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                if (v != null)
                {
                    dc.EmployeeMasters.Remove(v);
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
        }
    }
}
===============================
Model Class -- CLass
===============================
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace UniqDataMvc.Models
{
    [MetadataType(typeof(EmployeeMetadata))]
    public partial class EmployeeMaster
    {
        public string DepartmentName { get; set; }
    }

    public class EmployeeMetadata
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide first name")]
        public string Name { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please Select department")]
        public int depId { get; set; }

        [Required(ErrorMessage = "Email Required.")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Email is not valid")]
        public string Email { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide Mobile No")]
        public string MobileNo { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide Birthdate")]
        public string Birthdate { get; set; }
    }
}
===============================
Index.cshtml - List -- View
===============================

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
    <link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
    <style>
        span.field-validation-error {
            color: red;
        }
    </style>
</head>
<body>
    <div style="width:90%; margin:0 auto" class="tablecontainer">
        <a class="popup btn btn-primary" href="/home/save/0" style="margin-bottom:20px; margin-top:20px;">Add New Employee</a>
        <table id="myDatatable">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>dep Name</th>
                    <th>Email</th>
                    <th>MobileNo</th>
                    <th>Birthdate</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
        </table>
    </div>

    <script src="~/Scripts/jquery-3.1.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

    <script>
        $(document).ready(function () {
            var oTable = $('#myDatatable').DataTable({
                "ajax": {
                    "url" : '/home/GetEmployees',
                    "type" : "get",
                    "datatype" : "json"
                },
                "pageLength": 5,
                "columns": [
                    { "data": "Name", "autoWidth": true },
                    //{ "data": "depId", "autoWidth" : true},
                    { "data": "DepartmentName", "autoWidth": true},
                    { "data": "Email", "autoWidth": true },
                    { "data": "MobileNo", "autoWidth": true },
                    { "data": "Birthdate", "autoWidth": true },
                    {
                        "data": "EmpId", "width": "50px", "render": function (data) {
                            return '<a class="popup" href="/home/save/'+data+'">Edit</a>';
                        }
                    },
                    {
                        "data": "EmpId", "width": "50px", "render": function (data) {
                            return '<a class="popup" href="/home/delete/' + data + '">Delete</a>';
                        }
                    }
                ]
            })
            $('.tablecontainer').on('click', 'a.popup', function (e) {
                debugger
                e.preventDefault();
                OpenPopup($(this).attr('href'));
            })
            function OpenPopup(pageUrl) {
                debugger
                var $pageContent = $('<div/>');
                $pageContent.load(pageUrl, function () {
                    $('#popupForm', $pageContent).removeData('validator');
                    $('#popupForm', $pageContent).removeData('unobtrusiveValidation');
                   // $.validator.unobtrusive.parse('form');

                });

                $dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
                          .html($pageContent)
                          .dialog({
                              draggable : false,
                              autoOpen : false,
                              resizable : false,
                              model : true,
                              title:'Popup Dialog',
                              height : 550,
                              width : 600,
                              close: function () {
                                  $dialog.dialog('destroy').remove();
                              }
                          })

                $('.popupWindow').on('submit', '#popupForm', function (e) {
                    debugger
                    var url = $('#popupForm')[0].action;
                    $.ajax({
                        type : "POST",
                        url : url,
                        data: $('#popupForm').serialize(),
                        success: function (data) {
                            if (data.status) {
                                $dialog.dialog('close');
                                oTable.ajax.reload();
                            }
                        }
                    })

                    e.preventDefault();
                })

                $dialog.dialog('open');
            }
        })
    </script>
</body>
</html>
===============================
Save.cshtml - IU Functionality -- View
===============================
@model UniqDataMvc.Models.EmployeeMaster

<h2>Save</h2>

@using (Html.BeginForm("save", "home", FormMethod.Post, new { id = "popupForm" }))
{
    if (Model != null && Model.EmpId > 0)
    {
        @Html.HiddenFor(a => a.EmpId)
    }

    <div class="form-group">
        <label>First Name</label>
        @Html.TextBoxFor(a => a.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Name)
    </div>
    <div class="form-group">
        <label>Department Name</label>
        @Html.DropDownListFor(x => x.depId, new SelectList(ViewBag.deptList, "DepId", "DepName"), "Select", htmlAttributes: new { @class = "select form-control" })
        @Html.ValidationMessageFor(a => a.depId)
    </div>
    <div class="form-group">
        <label>Email</label>
        @Html.TextBoxFor(a => a.Email, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Email)
    </div>
    <div class="form-group">
        <label>MobileNo</label>
        @Html.TextBoxFor(a => a.MobileNo, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.MobileNo)
    </div>
    <div class="form-group">
        <label>Birthdate</label>
        @Html.TextBoxFor(a => a.Birthdate, new { @class = "form-control",type="date" })
        @Html.ValidationMessageFor(a => a.Birthdate)
    </div>
 

    <div>
        <input type="submit" value="Save" />
    </div>
}

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
===============================
CommonFunction - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace UniqDataMvc.DataService
{
    public static class CommmanFunction
    {
        public static List<T> ConvertToList<T>(this DataTable dt)
        {
            List<T> data = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                T item = GetItem<T>(row);
                data.Add(item);
            }
            return data;
        }
        public static T GetItem<T>(DataRow dr)
        {
            Type temp = typeof(T);
            T obj = Activator.CreateInstance<T>();

            foreach (DataColumn column in dr.Table.Columns)
            {
                foreach (PropertyInfo pro in temp.GetProperties())
                {
                    if (pro.Name == column.ColumnName)
                    {
                        if (!string.IsNullOrEmpty(Convert.ToString(dr[column.ColumnName])))
                        {
                            if (pro.PropertyType.Name == "String")
                                pro.SetValue(obj, Convert.ToString(dr[column.ColumnName]));
                            else
                                pro.SetValue(obj, dr[column.ColumnName]);
                        }
                    }
                    else
                        continue;
                }
            }
            return obj;
        }
    }
}
===============================
CreatePara - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace UniqDataMvc.DataService
{
    public static class CreatePara
    {
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, string paraVal, int size = 50, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.Size = size;
            para.SqlDbType = System.Data.SqlDbType.NVarChar;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, int paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Int;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, decimal paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Decimal;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, float paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Float;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, DateTime paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.DateTime;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, System.Data.DataTable paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Structured;
            para.Direction = dir;
            return para;
        }
    }
}
===============================
Dalc - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;

namespace UniqDataMvc.DataService
{
    public class dalc
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dalc_Conn"].ConnectionString);
        // SqlConnection conn;

        public dalc()
        {
            //conn.ConnectionString = ConfigurationSettings.AppSettings["myconn"];


            // conn.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

        }

        public DataSet selectbyquery(string str)
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandText = str.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

        public DataTable selectbyquerydt(string str)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = str.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(dt);
                return dt;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

       
    }
}

Demo for Repository Pattern in ASP.Net

----------------------------------------------------------- ----------------------------------------------------------- Repository Projec...