Friday, February 17, 2017

Asynchronous Requests for CRUD operations in Asp.Net MVC

In this post I will show how to use Asynchronous Requests in Asp.Net MVC. To continue this POST lets go through
for better understanding. we will change the above Synchronous post. In this post we can do CRUD operations using Bootstrap Modal, display data using Jquery DataTables and printing, exporting using jquery DataTables buttons.

Output:
According to Microsoft Asynchronous Requests means:
In web applications that sees a large number of concurrent requests at start-up or has a bursty load (where concurrency increases suddenly), making these web service calls asynchronous will increase the responsiveness of your application. An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a web service call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, a thread is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing and thread pool growth when there are many concurrent requests that invoke long-running operations.

  

public async Task<ActionResult> Create()
{ 
    var dept = await ent.Departments.ToListAsync();
    var viewModel = new EmployeeViewModel
    {
       Departments = dept
    };
    return PartialView("_CreateEmp", viewModel);
}


In the above Code async Task and await are the main important things. We can have multiple awaits in a method.
  • Create a Project
  • Use this Sql Server script for this post is HERE  and ADD ADO.Net Entity Data Modal in Models Folder as shown in the post CRUD operations in MVC with out writing any code
  • Add the following packages jQuery DataTables, jQuery DataTables buttons for printing and Exporting, Bootstrap 3.0+ 
  • In the scripts folder Add MyScripts folder. with in this folder add modalForms.js file. 
Add the following code in the BundleConfig.cs file and accordingly in respected folders.
  

bundles.Add(new ScriptBundle("~/bundles/DataTables").Include(
   "~/Scripts/DataTables/jquery.dataTables.js",
   "~/Scripts/DataTables/dataTables.jqueryui.js",
   "~/Scripts/DataTables/dataTables.bootstrap.js",
   //"~/Scripts/DataTables/dataTables.buttons.js",
   "~/Scripts/MyScripts/dataTables.buttons.js",
   "~/Scripts/jszip.js",
   //"~/Scripts/DataTables/buttons.pdfmake.js",
   "~/Scripts/MyScripts/pdfmake.js",
   "~/Scripts/DataTables/buttons.html5.js",
   "~/Scripts/DataTables/buttons.flash.js",
   "~/Scripts/DataTables/buttons.print.js",
   "~/Scripts/MyScripts/jquery.dataTables.columnFilter.js"));          

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
    "~/Scripts/bootstrap.js",
    "~/Scripts/bootstrap-datepicker.js",
    "~/Scripts/toastr.js",
    "~/Scripts/bootbox.js",
    "~/Scripts/respond.js"));

bundles.Add(new StyleBundle("~/Content/css").Include(
    "~/Content/bootstrap.css",
    "~/Content/toastr.css",
    "~/Content/font-awesome.min.css",
    "~/Content/bootstrap-datepicker3.css",
    "~/Content/DataTables/css/dataTables.bootstrap.css",
    "~/Content/DataTables/css/buttons.dataTables.css",
    "~/Content/DataTables/css/buttons.bootstrap.css",
    "~/Content/site.css"));

Now add the below code in the header and body tags
  

@Styles.Render("~/Content/css")
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
@Scripts.Render("~/bundles/modernizr")

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/DataTables")
<script src="~/Scripts/MyScripts/modalForm.js"></script>
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>

Create a folder ViewModels and ADD the following 3 Classes as shown
  

public class EmployeeVM
{
 public int ID { get; set; }

 [Required]
 public string FirstName { get; set; }

 [Required]
 public string LastName { get; set; }

 [Required]
 public string Gender { get; set; }

 public Nullable Salary { get; set; }

 [Required]
 [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
 public System.DateTime DOJ { get; set; }

 [Required]
 public Nullable DeptID { get; set; }

 public string DeptName { get; set; }
}

public class EmployeeViewModel
{
 public EmployeeVM Employee { get; set; }
 public IEnumerable Departments { get; set; }
}

public class DepartmentVM
{
 public int DeptID { get; set; }

 [Required]
 public string DeptName { get; set; }
}

Now replace HomeController with below code
  

using MVC_AccountPopUpAsync.Models;
using MVC_AccountPopUpAsync.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using System.Net;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Linq.Dynamic;
using System.Threading.Tasks;

namespace MVC_AccountPopUpAsync.Controllers
{
    public class HomeController : Controller
    {
        #region Constructor

        private EmployeeDBEntities ent;
        public HomeController()
        {
            ent = new EmployeeDBEntities();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
                ent.Dispose();
            base.Dispose(disposing);
        }

        #endregion

        public ActionResult Index()
        {
            //IEnumerable<department> deptList = ent.Departments.ToList();
            //var deptRslt = deptList.Select(x => Mapper.Map<departmentvm>(x)).ToList();

            //IEnumerable<departmentvm> Rslt = ent.Departments.ToList()
            //                                    .Select(Mapper.Map<department departmentvm="">).ToList();

            //var dep = ent.Departments.SingleOrDefault(x => x.DeptID == 2);
            //DepartmentVM deptVM = Mapper.Map<department departmentvm="">(dep);


            //var qqq = ent.Employees.OrderBy(x => x.FirstName).Skip(10).Take(100).ToList().Sum(x => x.Salary);

            return View();
        }

        [HttpPost]
        public async Task<ActionResult> getEmployee()
        {
            try
            {
                var Draw = Request.Form.GetValues("draw").FirstOrDefault();
                var Start = Request.Form.GetValues("start").FirstOrDefault();
                var Length = Request.Form.GetValues("length").FirstOrDefault();

                var SortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][data]").FirstOrDefault();
                var SortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();

                var firstName = Request.Form.GetValues("columns[1][search][value]").FirstOrDefault();
                var lastName = Request.Form.GetValues("columns[2][search][value]").FirstOrDefault();
                var gender = Request.Form.GetValues("columns[3][search][value]").FirstOrDefault();
                var sal = Request.Form.GetValues("columns[4][search][value]").FirstOrDefault();
                var joinDate = Request.Form.GetValues("columns[5][search][value]").FirstOrDefault();
                var deptName = Request.Form.GetValues("columns[6][search][value]").FirstOrDefault();

                DateTime DJ = DateTime.MinValue;
                if (joinDate != "")
                    DJ = joinDate.ToDateHifenddMMyyyy();

                int PageSize = Length != null ? Convert.ToInt32(Length) : 0;
                int Skip = Start != null ? Convert.ToInt32(Start) : 0;
                int TotalRecords = 0;

                IEnumerable<employeevm> emp = await (from e in ent.Employees
                                                     join d in ent.Departments on e.DeptID equals d.DeptID
                                                     where
                                                     e.FirstName.Contains(firstName) &&
                                                     e.LastName.Contains(lastName) &&
                                                     e.Gender.StartsWith(gender) &&
                                                     e.Salary.ToString().Contains(sal) &&
                                                     EntityFunctions.TruncateTime(e.DOJ) >= DJ &&
                                                     d.DeptName.Contains(deptName)
                                                     select new EmployeeVM
                                                     {
                                                         ID = e.ID,
                                                         FirstName = e.FirstName,
                                                         LastName = e.LastName,
                                                         Gender = e.Gender,
                                                         Salary = e.Salary,
                                                         DOJ = e.DOJ,
                                                         DeptName = d.DeptName
                                                     }).ToListAsync();

                if (!(string.IsNullOrEmpty(SortColumn) && string.IsNullOrEmpty(SortColumnDir)))
                {
                    emp = emp.OrderBy(SortColumn + " " + SortColumnDir).ToList();
                }

                TotalRecords = emp.ToList().Count();
                var NewItems = emp.Skip(Skip).Take(PageSize == -1 ? TotalRecords : PageSize).ToList();

                return Json(new { draw = Draw, recordsFiltered = TotalRecords, recordsTotal = TotalRecords, data = NewItems }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return CommonModel.getError(ex);
            }
        }

        public async Task<ActionResult> Create()
        {
            try
            {
                getGender();
                var dept = await ent.Departments.ToListAsync();
                var viewModel = new EmployeeViewModel
                {
                    Departments = dept
                };
                return PartialView("_CreateEmp", viewModel);
            }
            catch (Exception ex)
            {
                return CommonModel.getError(ex);
            }
        }

        [HttpPost]
        public async Task<ActionResult> Create(EmployeeViewModel evm)
        {
            try
            {
                getGender();
                var dept = ent.Departments.ToList();
                evm.Departments = dept;
                if (ModelState.IsValid)
                {
                    //Employee newEmp = new Employee();
                    //Mapper.Map(evm.Employee, newEmp);
                    //ent.Employees.Add(newEmp);
                    //ent.SaveChanges();

                    Employee emp = Mapper.Map<employee>(evm.Employee);
                    ent.Employees.Add(emp);
                    await ent.SaveChangesAsync();
                    return Json(new { success = true, message = "Saved Successfully." });
                }
                return PartialView("_CreateEmp", evm);
            }
            catch (Exception ex)
            {
                return CommonModel.postError(ex);
            }
        }

        public async Task<ActionResult> Edit(int? Id)
        {
            try
            {
                if (Id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Employee emp = await ent.Employees.FindAsync(Id);
                if (emp == null)
                    return HttpNotFound();
                EmployeeViewModel viewModel = new EmployeeViewModel()
                {
                    Departments = ent.Departments.ToList(),
                    Employee = Mapper.Map<employee employeevm="">(emp)
                };
                getGender();
                //return PartialView("_EditEmp", viewModel);
                return PartialView("_CreateEmp", viewModel);
            }
            catch (Exception ex)
            {
                return CommonModel.getError(ex);
            }
        }

        public async Task<ActionResult> getEmpDetails(int? EmpID)
        {
            try
            {
                var rslt = await (from e in ent.Employees
                                  join d in ent.Departments on e.DeptID equals d.DeptID
                                  where e.ID == EmpID
                                  select new
                                  {
                                      Name = e.FirstName + " " + e.LastName,
                                      Gender = e.Gender,
                                      Sal = e.Salary,
                                      DOJ = e.DOJ,
                                      DeptName = d.DeptName
                                  }).FirstOrDefaultAsync();

                return Json(rslt, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return CommonModel.getError(ex);
            }
        }

        public async Task<ActionResult> deleteConfirmed(int? EmpID)
        {
            try
            {
                var rslt = await ent.Employees.FirstOrDefaultAsync(x => x.ID == EmpID);
                if (rslt != null)
                {
                    ent.Employees.Remove(rslt);
                    await ent.SaveChangesAsync();
                    return Json("Success", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return HttpNotFound();
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        [HttpPost]
        public async Task<ActionResult> Edit(EmployeeViewModel evm)
        {
            try
            {
                evm.Departments = await ent.Departments.ToListAsync();
                if (ModelState.IsValid)
                {
                    getGender();
                    Employee emp = Mapper.Map<employee>(evm.Employee);
                    ent.Entry(emp).State = EntityState.Modified;
                    await ent.SaveChangesAsync();

                    return Json(new { success = true, message = "Updated Successfully." });
                }
                //return PartialView("_EditEmp", evm);
                return PartialView("_CreateEmp", evm);
            }
            catch (Exception ex)
            {
                return CommonModel.postError(ex);
            }
        }


        #region Dept & Gender

        private void getGender()
        {
            List<selectlistitem> gender = new List<selectlistitem>();
            gender.Add(new SelectListItem() { Value = "Male", Text = "Male" });
            gender.Add(new SelectListItem() { Value = "Female", Text = "Female" });
            ViewBag.gender = gender;
        }

        private void getDept()
        {
            ViewBag.dept = ent.Departments.ToList();
        }

        #endregion

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

In the Index.cshtml file ADD the following code
  

@model IEnumerable<MVC_AccountPopUpAsync.ViewModels.EmployeeVM>
@{
    ViewBag.Title = "Home Page";
}

<div id="MyModal" class="modal fade in">
    <div class="modal-dialog">
        <div class="modal-content">
            <div id="MyModalContent"></div>
        </div>
    </div>
</div>
<br />
<p>
    @Html.ActionLink("ADD Employee", "Create", null, null, new { data_modal = "", id = "btnCreate", @class = "btn btn-primary" })
</p>

<div>
    <table id="tblEmployees" class="table table-striped table-hover table-bordered table-responsive">
        <thead>
            <tr>
                <th>Actions</th>
                @*<th>First Name<div style="display:none"> Extra title</div></th>*@
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Salary</th>
                <th>DOJ</th>
                <th>Dept Name</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Salary</th>
                <th>DOJ</th>
                <th>Dept Name</th>
            </tr>
        </tfoot>
    </table>
</div>
<style>
    /*Buttons to Right Side*/
    div.dt-buttons {
        float: right;
        position: relative;
        margin-left: 10px;
    }
    /*Table Info to right*/
    div.dataTables_wrapper div.dataTables_info {
        float: left;
        padding-top: 8px;
        white-space: nowrap;
    }
</style>
@section Scripts{
    <script>
        //https://codepen.io/someatoms/pen/epNqQO
        var table;
        $(document).ready(function () {
            $('#tblEmployees tfoot th').each(function () {
                var title = $(this).text();
                if ($(this).index() == 0)
                    $(this).html('<input class="FClass" readonly style="width:80px;" type="text" id="' + title.replace(' ', '_') + '" placeholder="" />');
                //else if(title == "DOJ")
                //    $(this).html('<input class="FClass" readonly style="width:inherit;" type="text" id="' + title.replace(' ', '_') + '" placeholder="Search ' + title + '" />');
                else
                    $(this).html('<input class="FClass" style="width:inherit;" type="text" id="' + title.replace(' ', '_') + '" placeholder="Search ' + title + '" />');

            });

            table = $('#tblEmployees').DataTable({
                "ordering": true,
                "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                "pagingType": "full_numbers",
                "order": [[1, "asc"]], // Default Sorting
                "scrollY": "300px",
                "scrollX": true,
                "dom": 'Blrtip', // Hides Default Search
                //"dom": '<"floatRight"B><"clear">lrtip', // Didnt Worked to float Buttons Right Side
                //"bFilter":false, // Disables Filter
                "bAutoWidth": false,

                "processing": true,
                "serverSide": true,
                "orderMulti": false,

                "ajax": {
                    "url": "/Home/getEmployee",
                    "type": "POST",
                    "datatype": "json"
                },
                //buttons: ['copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5', 'print'],
                buttons: [
                            {
                                extend: 'copyHtml5',
                                text: '<i class="fa fa-files-o"></i>',
                                titleAttr: 'Copy'
                            },
                            {
                                extend: 'excelHtml5',
                                text: '<i class="fa fa-file-excel-o"></i>',
                                titleAttr: 'Excel',
                                title: 'Sample Excel Title Rows : ',// + table.data().length + '',
                                message: 'This is a Excel Sample Message',
                                exportOptions: {
                                    columns: [1, 2, 3, 4, 5, 6],
                                    orthogonal: 'export'
                                },
                                customize: function (xlsx) {
                                    var sheet = xlsx.xl.worksheets['sheet1.xml'];

                                    //$('row c[r^="C"]', sheet).attr('s', '2');//Bold All rows of a column
                                    $('row c[r*="5"]', sheet).attr('s', '25'); // Draw Border for row 5

                                    //$('row c[r^="A"]', sheet).attr('s', '2'); // 1 = Empty, 2 = Bold, 3 = Italic, 4 = underline, 5 = background cement
                                }
                            },
                            {
                                extend: 'csvHtml5',
                                text: '<i class="fa fa-file-text-o"></i>',
                                titleAttr: 'CSV',
                                title: 'Sample CSV Title',
                                exportOptions: {
                                    columns: [1, 2, 3, 4, 5, 6]
                                },
                                message: 'This is a CSV Sample Message'
                            },
                            {
                                extend: 'pdfHtml5',
                                text: '<i class="fa fa-file-pdf-o"></i>',
                                titleAttr: 'PDF',
                                title: 'Sample PDF Title',
                                orientation: 'portrait',
                                defaultStyle: {
                                    alignment: 'center',
                                },
                                exportOptions: {
                                    columns: [1, 2, 3, 4, 5, 6]
                                },
                                message: 'This is a PDF Sample Message'
                            },
                            {
                                extend: 'print',
                                text: '<i class="fa fa-print"></i>',
                                titleAttr: 'PRINT',
                                title: 'Sample Print Title',
                                orientation: 'portrait',
                                defaultStyle: {
                                    alignment: 'center',
                                },
                                exportOptions: {
                                    columns: [1, 2, 3, 4, 5, 6]
                                },
                                message: 'This is a Print Sample Message'
                            }
                ],
                //buttons: ['copy', 'excel', 'csv', 'pdf', 'print'],
                //buttons: [
                //            {
                //                extend: 'copy',
                //                text: '<i class="fa fa-files-o"></i>',
                //                titleAttr: 'Copy'
                //            },
                //            {
                //                extend: 'excel',
                //                text: '<i class="fa fa-file-excel-o"></i>',
                //                titleAttr: 'Excel'
                //            },
                //            {
                //                extend: 'csv',
                //                text: '<i class="fa fa-file-text-o"></i>',
                //                titleAttr: 'CSV'
                //            },
                //            {
                //                extend: 'pdf',
                //                text: '<i class="fa fa-file-pdf-o"></i>',
                //                titleAttr: 'PDF'
                //            },
                //            {
                //                extend: 'print',
                //                text: '<i class="fa fa-print"></i>',
                //                titleAttr: 'PRINT',
                //                title: 'Sample Title',
                //                message:'This is a Sample Message'
                //            }
                //        ],
                "aoColumns": [
                    {
                        "data": null,
                        "bSearchable": false,
                        "sortable": false,
                        "sWidth": "20%",
                        "targets": -1,
                        "render": function (data, type, full) {
                            return "<a onclick='Edit(" + full['ID'] + ")' id='btnEdit" + full['ID'] + "' class='btn btn-success btn-xs'><i class='glyphicon glyphicon-pencil'></i></a>" +
                              " <button onclick='Delete(" + full['ID'] + ")' class='btn btn-danger btn-xs'><i class='glyphicon glyphicon-remove'></i></button>";
                        }
                    },
                    { "data": "FirstName" },
                    { "data": "LastName" }, 
                    { "data": "Gender", },
                    { "data": "Salary", },
                    {
                        "data": "DOJ",
                        "name": "DOJ",
                        "render": function (data, type, full) {
                            return DateFormat(data);
                        }
                    },
                    { "data": "DeptName", "autoWidth": true }
                ]
            });

            table.columns().every(function () {
                var that = this;

                $('input', this.footer()).on('keyup change', function (ev) {
                    if (that.search() !== this.value) { //for Every keypress
                        //if (ev.keyCode == 13) { //only on enter keypress (code 13)
                        that
                            .search(this.value)
                            .draw();
                    }
                });
            });
        });

        var Edit = function (ID) {
            $.ajaxSetup({ cache: false });
            var EditUrl = "/Home/Edit/" + ID;
            $("#MyModalContent").load(EditUrl, function () {
                $("#MyModalTitle").text('Update Employee');
                $("#btnSubmit").val('Update');
                $("#MyModal").modal({
                    //backdrop: 'static',
                    keyboard: false
                }, 'show');
                bindForm(this);
            });
            return false;
        }

        //#region Delete

        var Delete = function (ID) {
            var Msg = "";
            $.ajax({
                url: "/Home/getEmpDetails",
                type: "GET",
                data: { EmpID: ID },
                success: function (result) {
                    Msg = "Name : <b>" + result.Name + "</b>";
                    Msg += "<br/>Gender : " + result.Gender;
                    Msg += "<br/>Salary : " + result.Sal;
                    Msg += "<br/>DOJ : " + DateFormat(result.DOJ);
                    Msg += "<br/>Department Name : " + result.DeptName;

                    bootbox.confirm({
                        title: "Sample Title",
                        message: Msg,
                        buttons: {
                            confirm: {
                                label: 'Yes',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: 'No',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                deleteConfirmed(ID);
                            }
                        }
                    });

                },
                error: function (error) {
                    console.log(error);
                    alert(error)
                }
            });
        }

        var deleteConfirmed = function (ID) {
            $.ajax({
                url: "/Home/deleteConfirmed",
                type: "GET",
                data: { EmpID: ID },
                success: function (result) {

                    toastr.success(result + ' Deleted Successfully.');
                    table.draw();
                },
                error: function (error) {
                    console.log(error);
                    alert(error)
                }
            });
        }

        function DateFormat(data) {
            var data1 = data.replace("/Date(", "").replace(")/", "");
            var date = new Date(parseInt(data1));
            var month = date.getMonth() + 1;
            return date.getDate() + "-" + (month.toString().length > 1 ? month : "0" + month) + "-" + date.getFullYear();
        }

        //#endregion Delete

        $(document).ready(function () {

            $('#DOJ').attr("readonly","readonly").datepicker({
                format: 'dd-mm-yyyy',
                //format: 'mm/dd/yyyy',
                autoclose: true,
                clearBtn: true,
                todayHighlight: true,
                //todayBtn: true,
                todayBtn: 'linked',
                orientation: "top left"
            });

        });

    </script>

}

Create _CreateEmp.cshtml file in views/home folder and add the below code in it.
  

@model MVC_AccountPopUpAsync.ViewModels.EmployeeViewModel

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h4 class="modal-title" id="MyModalTitle">Add New Employee</h4>
</div>

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "CreateEmp" }))
{
    @Html.AntiForgeryToken()

    <div class="modal-body">

        <div class="form-horizontal">
            @Html.HiddenFor(m => m.Employee.ID)
            @*@Html.ValidationSummary(true, "", new { @class = "text-danger" })*@
            <div class="form-group">
                @Html.LabelFor(m => m.Employee.FirstName, htmlAttributes: new { @class = "control-label col-sm-3" })
                <div class="col-sm-9">
                    @Html.EditorFor(m => m.Employee.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(m => m.Employee.FirstName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.Employee.LastName, htmlAttributes: new { @class = "control-label col-sm-3" })
                <div class="col-sm-9">
                    @Html.EditorFor(m => m.Employee.LastName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(m => m.Employee.LastName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.Employee.Gender, htmlAttributes: new { @class = "control-label col-sm-3" })
                <div class="col-sm-9">
                    @Html.DropDownListFor(m => m.Employee.Gender,
                    new SelectList((IEnumerable<SelectListItem>)ViewBag.gender, "Value", "Text"), "-- Select gender --",
                    htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Employee.Gender, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.Employee.Salary, htmlAttributes: new { @class = "control-label col-sm-3" })
                <div class="col-sm-9">
                    @Html.EditorFor(m => m.Employee.Salary, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(m => m.Employee.Salary, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.Employee.DOJ, htmlAttributes: new { @class = "control-label col-sm-3" })
                <div class="col-sm-9">
                    @Html.EditorFor(m => m.Employee.DOJ, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(m => m.Employee.DOJ, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(m => m.Employee.DeptID, htmlAttributes: new { @class = "control-label col-sm-3" })
                <div class="col-sm-9">
                    @Html.DropDownListFor(m => m.Employee.DeptID, new SelectList(Model.Departments, "DeptID", "DeptName"),
                    "-- Select Department --", htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Employee.DeptID, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
    </div>

    <div class="modal-footer">
        <button type="button" class="btn" data-dismiss="modal">Cancel</button>
        <input type="submit" class="btn btn-primary" value="Save" id="btnSubmit" />
    </div>
}

<script>
    $(document).ready(function () {
        $.validator.unobtrusive.parse('#CreateEmp');
        $("#btnSubmit").click(function () {
            if (!$("#CreateEmp").valid()) {
                return false;
            }
        });

        $('#Employee_DOJ').datepicker({
            //format: 'dd-mm-yyyy',
            format: 'mm/dd/yyyy',
            autoclose: true,
            clearBtn: true,
            todayHighlight: true,
            //todayBtn: true,
            todayBtn: 'linked',
            orientation: "top left"
        });
    });
</script>

Add the below code in the recently created modalForms.js file
  

$(function () {
    $.ajaxSetup({ cache: false });
    $("a[data-modal]").on("click", function (e) {
        //e.preventDefault();
        var urlPath = this.href;
        var CntrlType = $("#MyModal").attr('type');
        $("#MyModalContent").load(urlPath, function () {

            $("#MyModal").modal({
                //backdrop: 'static',
                keyboard: false
            }, 'show');
            bindForm(this);
        });
        return false;
    });
});

function bindForm(dialog) {
    $('form', dialog).submit(function () {
        //$.validator.unobtrusive.parse($('form'));
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $("#MyModal").modal('hide');
                    toastr.success(result.message);
                    table.draw();
                    //location.reload();
                }
                else {
                    $("#MyModal").modal('show');
                    //$("#MyModalContent").html(result);
                    toastr.error(result.ErrorMessage);
                    bindForm(dialog);
                }
            },
            error: function (xml, message, text) {
                toastr.error("Msg: " + message + ", Text: " + text);
            }
        });
        return false;
    });
}


Happy Coding

No comments:

Post a Comment