Building a CRUD Application with Ag-Grid

To Create Crud operation In Ag-Grid using C# MVC here Is a Download Link Click here..

Bundle Config


bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                         "~/Scripts/jquery-1.12.4.js",
                        "~/Scripts/jquery-ui-1.12.1.js",
                        "~/Scripts/bootstrap.js",
                         "~/Scripts/jquery.validate*",
                        "~/Scripts/jquery.validate.unobtrusive.js",
                        "~/Scripts/sweet-alert.min.js"
                        ));


bundles.Add(new StyleBundle("~/Content/css").Include(
                       "~/Content/bootstrap.css",
                      "~/Content/themes/base/jquery-ui.css",
                       "~/Content/sweet-alert.css",

                      "~/Content/site.css"));


Web.config 

  <add name="con1" connectionString="Data Source=SA-PC;Initial Catalog=Test;Integrated Security=SSPI" providerName="System.Data.SqlClient" />



Index.CShtml


<style>
 
.ag-layout-normal .ag-root-wrapper-body {
        height: 100% !important;
    }

    .ag-layout-normal .ag-body {
        height: 100% !important;
    }

</style>


<div class="container-fluid">
    <div class="row">

        <h4>Demo</h4>
        <hr />

        <div>
            <button type="button" class="btn rec_add_btn" id="addnew" onclick="AddEntry()"><i class="glyphicon glyphicon-plus"></i> Add Entry</button>
        </div>

        <div class="row  divAddEdit hide">
            <div id="divAddEdit" class="col-md-12">
                @{Html.RenderAction("AddEdit", "Home");}
            </div>
        </div>
        <div class="row">
            <div id="divDetail" class="col-md-12">
                @*@{Html.RenderAction("Details", "Home");}*@
                <div class="clearfix"></div>
                <div class="table_div tablePartHeight pos_rel z_index0" id="list">
                    <div class="col-xs-12 height100 no-padding">
                        <div id="myGrid" class="ag-theme-fresh agMainGridWithFooter noFooter"></div>
                    </div>
                  
                </div>
            </div>
        </div>
    </div>
</div>


// Code For AgGrid Bind here

<script>
    var columnDefs = [];
    var gridOptions = {};
    var dataFooter = {
        RN: 0,
        Action: ''
    };
    var RegisterList = [];
    columnDefs = [
                    { headerName: 'Sr.', field: 'RN', width: 60, headerClass: 'text-center' },
                    { headerName: 'Profile', field: 'ProfileImage', width: 150, headerClass: 'text-center', cellRenderer: 'RendererProfileImage' },
                    { headerName: 'Name', field: 'Name', width: 150, headerClass: 'text-center' },
                    { headerName: 'Email', field: 'Email', width: 150, headerClass: 'text-center' },
                    { headerName: 'Department', field: 'DepartmentName', width: 150, headerClass: 'text-center' },
                    { headerName: 'Language', field: 'LanguagesName', width: 150, headerClass: 'text-center' },
                    { headerName: 'Gender', field: 'Gender', width: 150, headerClass: 'text-center' },
                    { headerName: 'MobileNo', field: 'MobileNumber', width: 150, headerClass: 'text-center' },
                    { headerName: 'DateOfBirth', field: 'DateOfBirth', width: 150, headerClass: 'text-center' },
                    { headerName: 'Salary', field: 'Salary', width: 150, headerClass: 'text-right' },
                    { headerName: 'Action', field: 'Action', pinned: 'right', width: 150, headerClass: 'text-center', cellRenderer: 'RendererAction' },
    ]

    gridOptions = {
        columnDefs: columnDefs,
        enableFilter: true,
        enableRangeSelection: true,
        enableSorting: true,
        enableColResize: true,
        components: {
            RendererProfileImage: function (params) {
                var str = "";
                if (params.data.ProfileImage != undefined && params.data.ProfileImage != '') {
                    str = '<img src="/Profile/Images/' + params.data.ProfileImage + '"   width="50px" height="50px"/>';
                }

                return '<div class="Images"><center>' + str + '</center></div> ';
            },
            RendererAction: function (params) {
                var str = "";

                if (params.data.Name != undefined && params.data.Name != '') {
                    str = '<a onClick="EditEntry(' + params.data.RegistrationID + ',' + params.rowIndex + ',' + params.data.RN + ')" ><i class="btn btn-xs rec_edit_btn glyphicon glyphicon-pencil"></i></a> |';
                    str += '<i class="btn btn-xs rec_delete_btn glyphicon glyphicon-remove" onClick ="DeleteEntry(' + params.data.RegistrationID + ',' + params.rowIndex + ')" ></i>';

                }

                return '<div class="action_btn"><center>' + str + '</center></div> ';
            }
        }
    };
    setParameterRequest();

    document.addEventListener('DOMContentLoaded', function () {
        var gridDiv = document.querySelector('#myGrid');
        new agGrid.Grid(gridDiv, gridOptions);
    });
    function AddEntry() {
        $(".divAddEdit").removeClass("hide");
        $("#addnew").addClass("hide");
    }
    function setParameterRequest() {
        var ApiRequest = {
            PageNumber: 1,
            PageSize: 5000
        }
        GridData(ApiRequest);
    }
    function GridData(ApiRequest) {
        //  $("#grid-loading").show();
        $.ajax({
            url: '/Home/EmpList',
            type: 'POST',
            dataType: 'json',
            data: ApiRequest,
            success: function (Data) {
                //debugger
                GridRefresh();
                dataFooter.RN = "#" + (Data.Data.List.length);
                var list = []
                list.push(dataFooter);
                //  gridOptions.api.setPinnedBottomRowData(list);
                gridOptions.api.setRowData(Data.Data.List);
                //var tableHeaderHeight = $('.ag-header').height();
                //var tableBodyHeight = $('.ag-body.ag-row-animation').css('height', 'calc(100% - ' + tableHeaderHeight + 'px)');
                //$(".ag-body-viewport").addClass("scrollbarDefaultColor thik display_inlineBlock width_100");
                //$("#grid-loading").hide();
            }
        })
    }
    function GridRefresh() {
        if (gridOptions.api.isQuickFilterPresent()) {
            gridOptions.api.setQuickFilter('');
        }
        gridOptions.api.setFilterModel(null);
        gridOptions.api.setSortModel(null);
        gridOptions.columnApi.setRowGroupColumns([]);
    }

    function OnSuccess(d) {
        if (d == "Success") {
            clear();
            BindGrid();
        }
        else if (d = "Duplication") {
            swal('This Entry Is Already Inserted.')
        }
        else {
            SaveErrorSweetAltMessage();
        }
    }

    function BindGrid() {

        $.ajax({
            url: '/Home/Details',
            type: 'POST',
            dataType: 'html',
            data: '',
            success: function (Data) {
                $("#divDetail").html(Data);
            }
        })
    }

    function DeleteEntry(RegisterID, i) {
        swal({
            title: 'Are you Sure, You want to delete it?',
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            $.post('/Home/Delete', { id: RegisterID }, function (d) {
                if (d == "Success") {
                    setParameterRequest();
                    swal('Deleted!', 'Your record has been deleted.', 'success');
                }
                else {
                    swal('', 'Delete again.', 'warning');
                }
            });

        });
    }

    function EditEntry(RegisterID, i, RN) {
        $(".divAddEdit").removeClass("hide");
        $("#addnew").addClass("hide");
        var editRow = gridOptions.api.getDisplayedRowAtIndex(i).data;
        $.post('/Home/GetEditEmpDetails', { id: RegisterID }, function (d) {
            if (d.Data.Result == "OK") {            
                $('#RegistrationID').val(d.Data.List[0].RegistrationID);
                $('#ddlSalutation').val(d.Data.List[0].Salutation);
                $('#txtFirstName').val(d.Data.List[0].FirstName);
                $('#txtLastName').val(d.Data.List[0].LastName);
                $('#txtEmail').val(d.Data.List[0].Email);
                $('#txtMobileNumber').val(d.Data.List[0].MobileNumber);
                $('#ddlDepartmentID').val(d.Data.List[0].DepartmentID);
                $('#ddlGender').val(d.Data.List[0].Gender);
                $('#ddlLanguagesID').val(d.Data.List[0].LanguagesID);
                $('#txtSalary').val(d.Data.List[0].Salary);
                $('#txtDateOfBirth').val(d.Data.List[0].DateOfBirth);
                $('#hndProfileImage').val(d.Data.List[0].ProfileImage);
            }
        });
        //$('#LabourRate').val(editRow.LabourRate);
       
        //$('#LabourID').val(editRow.LabourID);
    }
    function clear() {
        $('#ddlSalutation').val('');
        $('#txtFirstName').val('');
        $('#txtLastName').val('');
        $('#txtEmail').val('');
        $('#txtMobileNumber').val('');
        $('#ddlDepartmentID').val('');
        $('#ddlGender').val('');
        $('#ddlLanguagesID').val('');
        $('#txtSalary').val('');
        $('#txtDateOfBirth').val('');
        $('#txtAge').val('');
        $('#txtProfileImage').val('');
        makedatecontrol();
    }

    function OnFailure(response) {
        alert("Error occured.");
    }
</script>


_AddEdit.Cshtml

@model TestDemo.Models.Registration
<div class="col-md-12">
    @using (Ajax.BeginForm("Save", "Home", null, new AjaxOptions { HttpMethod = "POST", OnComplete = "OnSuccess" }, new { id = "frmroughpurchse", enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)

        @Html.AntiForgeryToken()


        <div class="col-md-12 form-horizontal">

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(c => c.RegistrationID, new { id = "RegistrationID" })
            <div class="col-md-3">
                <div class="form-group">
                    <label class="control-label">Salutation</label>
                    <div class="">
                        @Html.DropDownListFor(c => c.Salutation, new List<SelectListItem> { new SelectListItem { Text = "Mr", Value = "Mr" }, new SelectListItem { Text = "Mrs", Value = "Mrs" } }, "--Select Salutation--", new { tabindex = 1, @class = "form-control", @id = "ddlSalutation", @required = "required" })
                        @*@Html.EditorFor(model => model.Salutation, new { htmlAttributes = new { @id = "txtSalutation", @class = "form-control", @tabindex = "1", @required = "required" } })*@
                        @Html.ValidationMessageFor(model => model.Salutation, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("First Name:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @id = "txtFirstName", @class = "form-control", @tabindex = "2", @required = "required" } })
                        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Last Name:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @id = "txtLastName", @class = "form-control", @tabindex = "3", @required = "required" } })
                        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Email:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @id = "txtEmail", @class = "form-control", @tabindex = "4", @required = "required" } })
                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Mobile Number:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.EditorFor(model => model.MobileNumber, new { htmlAttributes = new { @id = "txtMobileNumber", @class = "form-control", @tabindex = "5", @required = "required" } })
                        @Html.ValidationMessageFor(model => model.MobileNumber, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Department:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.DropDownListFor(model => model.DepartmentID, ViewBag.Department as SelectList, "--Select Department--", new { tabindex = 6, @id = "ddlDepartmentID", @class = "form-control", @required = "required" })
                        @Html.ValidationMessageFor(model => model.DepartmentID, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Gender:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.DropDownListFor(model => model.Gender, new List<SelectListItem> { new SelectListItem { Text = "Male", Value = "Male" }, new SelectListItem { Text = "FeMale", Value = "FeMale" } }, "--Select Gender--", new { tabindex = 7, @class = "form-control", @id = "ddlGender", @required = "required" })
                        @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Languages:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.DropDownListFor(model => model.LanguagesID, ViewBag.Languages as SelectList, "--Select Languages--", new { tabindex = 8, @id = "ddlLanguagesID", @class = "form-control", @required = "required" })
                        @Html.ValidationMessageFor(model => model.LanguagesID, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Salary:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @id = "txtSalary", @class = "form-control decimalonly", @tabindex = "9", @required = "required" } })
                        @Html.ValidationMessageFor(model => model.Salary, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Date Of Birth:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.TextBoxFor(model => model.DateOfBirth, "{0:dd/MM/yyyy}", new { tabindex = "10", @class = "form-control datepickerdefaultcls", @id = "txtDateOfBirth", @required = "required", @autocomplete = "off" })
                        @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    @Html.Label("Age:", htmlAttributes: new { @class = "control-label" })
                    <div class="">
                        @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @id = "txtAge", @class = "form-control", @tabindex = "11", @required = "required" } })
                        @Html.ValidationMessageFor(model => model.Age, "", new { @class = "error" })
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label class="control-label">Profile Img</label>
                    <div class="input_div pos_rel">
                        @Html.TextBoxFor(c => c.ProfileImage, new { @class = "form-control", @id = "txtProfileImage", @type = "file", tabindex = 12 })
                        @Html.HiddenFor(c => c.ProfileImage,new {@id="hndProfileImage" })
                        @*@if (Model.RegistrationID > 0 && (Model.ProfileImage != "" && Model.ProfileImage != null))
                            {
                                <a target="/" href="../../Upload/Invoice/@Model.ProfileImage"> <i class="btn btn-xs btnimgdownload text-primary glyphicon glyphicon-download-alt imgdownload"></i></a>
                            }*@
                    </div>
                </div>
            </div>
            <div class="col-md-3 text-center">

                <div class="form-group">
                    <div>
                        <input type="submit" value="Save" class="btn btn-success" />
                        <button type="button" class="btn enter btn-default" onclick="Closed();">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    }
</div>

<script>
    $(document).ready(function () {
        makedatecontrol();
        $('#frmroughpurchse').submit(function (event) {
            event.preventDefault();
            if ($(this).valid()) {
                debugger

                var id = $("#RegistrationID").val();
                var validExts = new Array(".jpeg", ".jpg", ".png");
                var formdata = new FormData($(this).get(0));
                var fileUpload = $("#txtProfileImage").get(0);
                var files = fileUpload.files;
                if (files.length > 0) {
                    var fileExt = fileUpload.files[0].name;
                    fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
                    if (validExts.indexOf(fileExt) < 0) {
                        //  $('#savebtnhideshow').show();
                        $('.bottom_btn_bar img.loader_img').css("display", "none");
                        ShowSweetAltMessage("", "Invoice Images Incorrect file, the correct file type is " + validExts.toString() + " types.", "info");
                        return false;
                    }
                }
                //End File Oriented Code

                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: formdata,
                    processData: false,
                    contentType: false,
                    async: false,
                    success: function (d) {
                        if (d > 0) {
                            clear();
                            //BindGrid();
                            setParameterRequest();
                            if (id != null && id > 0) {
                                Closed();
                            }
                        }
                        else if (d == -1) {
                            alert("Duplicate");
                        }
                    },
                    failure: function (response) {

                    },
                    error: function (response) {

                    }
                });
            }
            return false;
        });

    });
    function makedatecontrol() {
        $(".datepickerdefaultcls").datepicker({ changeMonth: !0, changeYear: !0, dateFormat: "dd/mm/yy", yearRange: "1930:2030", autoclose: !0 }).on("changeDate", function (t) {
            debugger;
            getAge(t.value);
        })
    }
    function getAge(dateString) {
        var dates = dateString.split("/");
        var d = new Date();
        var userday = dates[0];
        var usermonth = dates[1];
        var useryear = dates[2];
        var curday = d.getDate();
        var curmonth = d.getMonth() + 1;
        var curyear = d.getFullYear();
        var age = curyear - useryear;
        if ((curmonth < usermonth) || ((curmonth == usermonth) && curday < userday)) {
            age--;
        }
        return age;
    }

    function Closed()
    {
        $(".divAddEdit").addClass("hide");
        $("#addnew").removeClass("hide");
    }
</script>


Registration Model


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace TestDemo.Models
{
    public class Registration
    {
        string SqlCon = ConfigurationManager.ConnectionStrings["con1"].ToString();
        public int RegistrationID { get; set; } = 0;

        [Required(ErrorMessage = "Please Select Salutation")]
        public string Salutation { get; set; }
        [Required(ErrorMessage = "Please Enter FirstName")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "Please Enter LastName")]
        public string LastName { get; set; }
        public string Email { get; set; }
        public int MobileNumber { get; set; }
        public Int16 DepartmentID { get; set; }
        public string Gender { get; set; }
        public Int16 LanguagesID { get; set; }
        public int Salary { get; set; }

        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public string DateOfBirth { get; set; }
        public Int16 Age { get; set; }
        public string ProfileImage { get; set; }


        public List<Registration> RList = new List<Registration>();


        public int Save(Registration obj)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Parameters.AddWithValue("@RegistrationID", obj.RegistrationID);
            cmd.Parameters.AddWithValue("@Salutation", obj.Salutation);
            cmd.Parameters.AddWithValue("@FirstName", obj.FirstName);
            cmd.Parameters.AddWithValue("@LastName", obj.LastName);
            cmd.Parameters.AddWithValue("@Email", obj.Email);
            cmd.Parameters.AddWithValue("@MobileNumber", obj.MobileNumber);
            cmd.Parameters.AddWithValue("@DepartmentID", obj.DepartmentID);
            cmd.Parameters.AddWithValue("@Gender", obj.Gender);
            cmd.Parameters.AddWithValue("@LanguagesID", obj.LanguagesID);
            cmd.Parameters.AddWithValue("@Salary", obj.Salary);
            cmd.Parameters.AddWithValue("@DateOfBirth", obj.DateOfBirth);
            cmd.Parameters.AddWithValue("@Age", obj.Age);
            cmd.Parameters.AddWithValue("@ProfileImage", obj.ProfileImage);


            return AddDataWithCommandObj_Int32("Registration_Detail_Insert_Update", cmd);

        }
        public int DeleteDetail(int id)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Parameters.AddWithValue("@RegistrationID", id);
            return Common.DeleteRecord("Registration_Detail_Delete", cmd);
        }
        public int AddDataWithCommandObj_Int32(string StoredProcedureName, SqlCommand cmd)
        {
            int ReturnID = 0;
            using (SqlConnection con = new SqlConnection(SqlCon))
            {
                con.Open();
                try
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = StoredProcedureName;
                    cmd.CommandTimeout = 300;
                    cmd.Connection = con;
                    ReturnID = (int)cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    ReturnID = -1;
                }
                cmd.Dispose();
                con.Close();
            }
            return ReturnID;
        }

        public int DeleteRecord(string storedProcedureName, SqlCommand cmd)
        {
            int returnId = 0;
            using (SqlConnection con = new SqlConnection(SqlCon))
            {
                con.Open();
                try
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = storedProcedureName;
                    cmd.CommandTimeout = 300;
                    cmd.Connection = con;
                    //cmd.ExecuteNonQuery();
                    returnId = (int)cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    //-1 duplicate
                    //-2 Noram Error
                    //-3 forign Key
                    //if(ex.Message)
                    returnId = -3;
                }
                cmd.Dispose();
                con.Close();

            }
            return returnId;
        }
    }
}


LargeJsonResult.Cs


using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace TestDemo.Models
{
    public class LargeJsonResult : JsonResult
    {
        const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
        public LargeJsonResult()
        {
            MaxJsonLength = 2147483647;
            RecursionLimit = 100;
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(JsonRequest_GetNotAllowed);
            }
            HttpResponseBase response = context.HttpContext.Response;
            if (!string.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = Convert.ToInt32(MaxJsonLength), RecursionLimit = Convert.ToInt32(RecursionLimit) };
                response.Write(serializer.Serialize(Data));


            }
        }
    }
}


Home Controller



using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestDemo.Models;

namespace TestDemo.Controllers
{
public class HomeController : Controller
    {
        string SqlCon = ConfigurationManager.ConnectionStrings["con1"].ToString();
        public ActionResult Index()
        {
            SqlCommand cmd = new SqlCommand();
            DataSet ds = GetAllList("BindDDL_List", cmd);
            ViewBag.Department = GetAllDDLList(ds.Tables[0]);
            ViewBag.Languages = GetAllDDLList(ds.Tables[1]);

            List<Registration> RegList = new List<Registration>();
            SqlCommand cmd1 = new SqlCommand();
            DataSet Ds = GetAllList("Registration_Detail_List", cmd1);
            if (Ds != null && Ds.Tables[0].Rows.Count > 0)
            {
                ViewBag.RegistrationList = GetAllRecordConvertList(Ds.Tables[0]);
            }
            else
            {
                ViewBag.RegistrationList = null;
            }

            return View();
        }
public static SelectList GetAllDDLList(DataTable dt, int[] selectedval = null)
        {
            if (dt != null)
            {
                List<SelectListItem> list = new List<SelectListItem>();
                foreach (DataRow row in dt.Rows)
                {
                    list.Add(new SelectListItem()
                    {
                        Text = row[1].ToString(),
                        Value = row[0].ToString()
                    });
                }
                if (selectedval != null)
                {
                    return new SelectList(list, "Value", "Text", selectedval);
                }
                else
                {
                    return new SelectList(list, "Value", "Text");
                }
            }
            return null;
        }

  [HttpPost]
        public ActionResult Save(Registration obj)
        {
            HttpFileCollectionBase files = Request.Files;
            if (files.Count > 0)
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    string path = Server.MapPath("~/Profile/Images/");
                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    HttpPostedFileBase FImage = files[i];
                    if (FImage != null && FImage.ContentLength > 0)
                    {
                        var ext = Path.GetExtension(FImage.FileName);
                        string FName = DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss") + ext;
                        FImage.SaveAs(Path.Combine(path, FName));
                        if (files.Keys[i].ToString() == "ProfileImage")
                        {
                            if (obj.ProfileImage != null && obj.ProfileImage != "")
                            {
                                string filePath = path + obj.ProfileImage.ToString();
                                if (System.IO.File.Exists(filePath))
                                {
                                    System.IO.File.Delete(filePath);
                                }
                            }
                            obj.ProfileImage = FName;
                        }
                    }
                }
            }
            Registration rejobj = new Registration();
            int ID = rejobj.Save(obj);
            if (ID > 0)
            {
                return Json(ID, "Success", JsonRequestBehavior.AllowGet);
            }
            else if (ID == -1)
            {
                return Json(ID, "Duplication", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(ID, "Failed", JsonRequestBehavior.AllowGet);
            }
        }

public JsonResult EmpDetails()
        {
           
            return Json("", JsonRequestBehavior.AllowGet);
        }
        public LargeJsonResult EmpList(int PageNumber, int PageSize, string Sorting = "", string search = "")
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Parameters.AddWithValue("@pageno", PageNumber);
            cmd.Parameters.AddWithValue("@pagesize", PageSize);
            cmd.Parameters.AddWithValue("@sortcolumn", Sorting);
            cmd.Parameters.AddWithValue("@filter", search);
            DataSet Ds = GetAllList("Registration_Detail_List", cmd);
            if (Ds.Tables.Count > 0)
            {
                var objlist = GetAllRecordConvertList(Ds.Tables[0]).ToList();
                return new LargeJsonResult { Data = Json(new { Result = "OK", List = objlist, Count = objlist.Count }) };
            }
            else
            {
                return new LargeJsonResult { Data = Json(new { Result = "Error", List = string.Empty, Count = 0 }) };
            }

        }
  public ActionResult Details()
        {
            List<Registration> RegList = new List<Registration>();
            SqlCommand cmd = new SqlCommand();
            DataSet Ds = GetAllList("Registration_Detail_List", cmd);
            if (Ds != null && Ds.Tables[0].Rows.Count > 0)
            {
                ViewBag.RegistrationList = GetAllRecordConvertList(Ds.Tables[0]);
            }
            else
            {
                ViewBag.RegistrationList = null;
            }

            return PartialView("_Detail");
        }

        public static DataSet GetAllList(string StoredProcedureName, SqlCommand cmd)
        {
            DataSet ds = new DataSet();
            try
            {
                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ToString()))
                {
                    con.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlDataAdapter adp = new SqlDataAdapter();
                    cmd.CommandText = StoredProcedureName;
                    cmd.CommandTimeout = 300;
                    cmd.Connection = con;
                    adp.SelectCommand = cmd;
                    adp.Fill(ds);
                    con.Close();
                }
            }
            catch (Exception ex) { }
            return ds;
        }
public static List<Dictionary<string, object>> GetAllRecordConvertList(DataTable dt)
        {
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return rows;
        }

        [HttpPost]
        public ActionResult GetEditEmpDetails(int id)
        {
            Registration objEmp = new Registration();

            if (id > 0)
            {
                SqlCommand cmd1 = new SqlCommand();
                cmd1.Parameters.AddWithValue("@RegistrationID", id);
                DataSet Ds = GetAllList("Registration_Detail_Get", cmd1);
                if (Ds.Tables.Count > 0)
                {
                    var objlist = GetAllRecordConvertList(Ds.Tables[0]).ToList();
                    return new LargeJsonResult { Data = Json(new { Result = "OK", List = objlist, Count = objlist.Count }) };
                }
                else
                {
                    return new LargeJsonResult { Data = Json(new { Result = "Error", List = string.Empty, Count = 0 }) };
                }

            }
            else
            {
                return new LargeJsonResult { Data = Json(new { Result = "Error", List = string.Empty, Count = 0 }) };
            }

            //   return PartialView("_AddEdit", objEmp);
        }
  [HttpPost]
        public ActionResult GetEmpDetails(int id)
        {
            Registration objEmp = new Registration();

            SqlCommand cmd = new SqlCommand();
            DataSet ds = GetAllList("BindDDL_List", cmd);
            ViewBag.Department = GetAllDDLList(ds.Tables[0]);
            ViewBag.Languages = GetAllDDLList(ds.Tables[1]);
            if (id > 0)
            {
                SqlCommand cmd1 = new SqlCommand();
                cmd1.Parameters.AddWithValue("@RegistrationID", id);
                DataSet Ds = GetAllList("Registration_Detail_Get", cmd1);
                if (Ds != null && Ds.Tables[0].Rows.Count > 0)
                {
                    objEmp.RegistrationID = Convert.ToInt32(Ds.Tables[0].Rows[0]["RegistrationID"].ToString());
                    objEmp.FirstName = Ds.Tables[0].Rows[0]["FirstName"].ToString();
                    objEmp.LastName = Ds.Tables[0].Rows[0]["LastName"].ToString();
                    objEmp.Gender = Ds.Tables[0].Rows[0]["Gender"].ToString();
                    objEmp.LanguagesID = Convert.ToInt16(Ds.Tables[0].Rows[0]["LanguagesID"].ToString());
                    objEmp.Salutation = Ds.Tables[0].Rows[0]["Salutation"].ToString();
                    objEmp.DateOfBirth = Ds.Tables[0].Rows[0]["DateOfBirth"].ToString();
                    objEmp.Age = Convert.ToInt16(Ds.Tables[0].Rows[0]["Age"].ToString());
                    objEmp.Email = Ds.Tables[0].Rows[0]["Email"].ToString();
                    objEmp.MobileNumber = Convert.ToInt32(Ds.Tables[0].Rows[0]["MobileNumber"].ToString());
                    objEmp.DepartmentID = Convert.ToInt16(Ds.Tables[0].Rows[0]["DepartmentID"].ToString());
                    objEmp.Salary = Convert.ToInt32(Ds.Tables[0].Rows[0]["Salary"].ToString());
                    objEmp.Age = Convert.ToInt16(Ds.Tables[0].Rows[0]["Age"].ToString());
                    objEmp.ProfileImage = Ds.Tables[0].Rows[0]["ProfileImage"].ToString();
                }

            }
            return PartialView("_AddEdit", objEmp);
        }

        public ActionResult AddEdit(int id = 0)
        {
            Registration objEmp = new Registration();

            SqlCommand cmd = new SqlCommand();
            DataSet ds = GetAllList("BindDDL_List", cmd);
            ViewBag.Department = GetAllDDLList(ds.Tables[0]);
            ViewBag.Languages = GetAllDDLList(ds.Tables[1]);
            if (id > 0)
            {
                SqlCommand cmd1 = new SqlCommand();
                cmd1.Parameters.AddWithValue("@RegistrationID", id);
                DataSet Ds = GetAllList("Registration_Detail_Get", cmd1);
                if (Ds != null && Ds.Tables[0].Rows.Count > 0)
                {
                    objEmp.DepartmentID = Convert.ToInt16(Ds.Tables[0].Rows[0]["DepartmentID"].ToString());

                }
            }
            return PartialView("_AddEdit", objEmp);


        }
  public ActionResult Delete(int id)
        {
            Registration rejobj = new Registration();
            int RetrunID = rejobj.DeleteDetail(id);
            if (RetrunID > 0)
            {
                return Json("Success", JsonRequestBehavior.AllowGet);
            }
            else if (RetrunID == -3)
            {
                return Json("FailedFK", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("Failed", JsonRequestBehavior.AllowGet);
            }

        }
    }
}



Comments

Popular posts from this blog

Private Chat Using Node js and socket.io with encrypt and decrypt message and insert into mongo db

How To Migrate MVC 3 Application To MVC 5

Populate a drop-down in Vue.js and Asp.net Core from an ajax call