Sunday, January 29, 2017

CRUD operations using Bootstrap Modal in Asp.Net MVC

In this post I will show how to CRUD operations in Asp.Net MVC using Bootstrap Modal and display records using Jquery DataTables with Exporting and printing.

Previously I had shown how to....
MVC:
Output:

AngularJS:
Create New Project in Visual studio 2015, using Asp.Net and MVC.
Ones it is created ADD jquery DataTables (latest version) using Package Manager.
ADD AutoMapper and configure as shown in the post How to use AutoMapper,
Add/Update Bootstrap to Bootstrap3, Add Bootbox.js, Toastr.js, bootstrap-datepicker.js, jquery.dataTables.columnFilter.js and related css. Configure them in BundleConfig.cs as shown below.
  

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/jszip.js",
   "~/Scripts/DataTables/buttons.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 scripts in _LayOut.cshtml page, CSS in the Header section and remaining under @Scripts.Render("~/bundles/jquery")
  

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/DataTables")
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>    

Sql server script for this post is HERE Add Entity Data Model in Models Folder as shown in the post
CRUD operations in MVC with out writing any code
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 DepartmentVM
{
 public int DeptID { get; set; }

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

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

Now in scripts folder add another folder name as MyScripts and ADD modalForm.js File and jquery.dataTables.columnFilter.js in it.
You can download jquery.dataTables.columnFilter.js file from HERE In modalForm.js file ADD the below Code.
  

$(function () {
    $.ajaxSetup({ cache: false });
    $("a[data-modal]").on("click", function (e) {
        $("#MyModalContent").load(this.href, function () {
            $("#MyModal").modal({
                //backdrop: 'static',
                keyboard: false
            }, 'show');
            bindForm(this);
        });
        return false;
    });
});

function bindForm(dialog)
{    
    $('form', dialog).submit(function () {
        $.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();
                }
                else {
                    //$("#MyModalContent").html(result);
                    $("#MyModal").modal('show');
                    toastr.error(result.ErrorMessage);
                    bindForm(dialog);
                }
            },
            error: function (xml, message, text) {
                toastr.error("Msg: " + message + ", Text: " + text);
            }
        });
        return false;
    });
}

Drag and drop this file on to _LayOut.cshtml, Replace the text in Index.cshtml file with below code.
  

@model IEnumerable<MVC_AccountPopUp.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>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Salary</th>
                <th>DOJ</th>
                <th>Dept Name</th>
                <th></th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Salary</th>
                <th>DOJ</th>
                <th>Dept Name</th>
                <th></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>
        var table;
        $(document).ready(function () {
            $('#tblEmployees tfoot th').each(function () {
                var title = $(this).text();
                $(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",
                "scrollY": "300px",
                "scrollX": true,
                "dom": 'Blrtip', // Hides Default Search

                "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',
                                message: 'This is a Excel Sample Message',
                                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*="3"]', sheet).attr('s', '25');
                                }
                            },
                            {
                                extend: 'csvHtml5',
                                text: '<i class="fa fa-file-text-o"></i>',
                                titleAttr: 'CSV',
                                title: 'Sample CSV Title',
                                message: 'This is a CSV Sample Message'
                            },
                            {
                                extend: 'pdfHtml5',
                                text: '<i class="fa fa-file-pdf-o"></i>',
                                titleAttr: 'PDF',
                                title: 'Sample PDF Title',
                                message: 'This is a PDF Sample Message'
                            },
                            {
                                extend: 'print',
                                text: '<i class="fa fa-print"></i>',
                                titleAttr: 'PRINT',
                                title: 'Sample Print Title',
                                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": "FirstName", "autoWidth": true },
                    { "data": "LastName", "autoWidth": true },
                    { "data": "Gender", "autoWidth": true },
                    { "data": "Salary", "autoWidth": true },
                    {
                        "data": "DOJ",
                        "name": "DOJ",
                        "render": function (data, type, full) {
                            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();
                        },
                        "autoWidth": true
                    },
                    { "data": "DeptName", "autoWidth": true },
                    {
                        "data": null,
                        "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>";
                        },
                        "bSearchable": true,
                        "sortable": false,
                        "autoWidth": false,
                        "sWidth": "20px"
                    }
                ]
            });

            table.columns().every(function () {
                var that = this;
                $('input', this.footer()).on('keyup change', function () {
                    if (that.search() !== this.value) {
                        that
                            .search(this.value)
                            .draw();
                    }
                });
            });
        });

        var Edit = function (ID) {
            $.ajaxSetup({ cache: false });
            var EditUrl = "/Home/Edit/" + ID;
            $("#MyModalContent").load(EditUrl, function () {
                $("#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[0].Name + "</b>";
                    Msg += "<br/>Gender : " + result[0].Gender;
                    Msg += "<br/>Salary : " + result[0].Sal;
                    Msg += "<br/>DOJ : " + DateFormat(result[0].DOJ);
                    Msg += "<br/>Department Name : " + result[0].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').datepicker({
                format: 'dd-mm-yyyy',
                //format: 'mm/dd/yyyy',
                autoclose: true,
                clearBtn: true,
                todayHighlight: true,
                //todayBtn: true,
                todayBtn: 'linked',
                orientation: "top left"
            });

        });

    </script>

}

In Views/Home folder add the following empty views. _CreateEmp.cshtml, _EditEmp.cshtml. In the HomeController.cs ADD the following methods.
  

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()
 {
  return View();
 }

 [HttpPost]
 public ActionResult getEmployee()
 {
  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[0][search][value]").FirstOrDefault();
  var lastName = Request.Form.GetValues("columns[1][search][value]").FirstOrDefault();
  var gender = Request.Form.GetValues("columns[2][search][value]").FirstOrDefault();
  var sal = Request.Form.GetValues("columns[3][search][value]").FirstOrDefault();
  var joinDate = Request.Form.GetValues("columns[4][search][value]").FirstOrDefault();
  var deptName = Request.Form.GetValues("columns[5][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 emp = (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
            }).ToList();

  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);
 }

 public ActionResult Create()
 {
  getGender();
  var dept = ent.Departments.ToList();
  var viewModel = new EmployeeViewModel
  {
   Departments = dept
  };
  return PartialView("_CreateEmp", viewModel);
 }

 [HttpPost]
 public ActionResult Create(EmployeeViewModel evm)
 {
  try
  {
   getGender();
   var dept = ent.Departments.ToList();
   evm.Departments = dept;
   if (ModelState.IsValid)
   {
    Employee emp = Mapper.Map(evm.Employee);
    ent.Employees.Add(emp);
    ent.SaveChanges();
    return Json(new { success = true, message = "Saved Successfully." });
   }
   return PartialView("_CreateEmp", evm);
  }
  catch (Exception ex)
  {
    return new JsonResult
    {
      Data = new { ErrorMessage = ex.Message, Success = false },
      ContentEncoding = System.Text.Encoding.UTF8,
      JsonRequestBehavior = JsonRequestBehavior.DenyGet
    };

  }
 }

 public ActionResult Edit(int? Id)
 {
  try
  {
   if (Id == null)
   {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
   }
   Employee emp = ent.Employees.Find(Id);
   if (emp == null)
    return HttpNotFound();
   EmployeeViewModel viewModel = new EmployeeViewModel()
   {
    Departments = ent.Departments.ToList(),
    Employee = Mapper.Map(emp)
   };
   getGender();
   return PartialView("_EditEmp", viewModel);
  }
  catch (Exception ex)
  {
   return null;
  }
 }

 public ActionResult getEmpDetails(int? EmpID)
 {
  try
  {
   var rslt = (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
      });

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

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

 [HttpPost]
 public ActionResult Edit(EmployeeViewModel evm)
 {
  try
  {
   evm.Departments = ent.Departments.ToList();
   if (ModelState.IsValid)
   {
    getGender();
    Employee emp = Mapper.Map(evm.Employee);
    ent.Entry(emp).State = EntityState.Modified;
    ent.SaveChanges();

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


 #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
}
In _CreateEmp.cshtml file add the below script
  

@model MVC_AccountPopUp.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.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.DropDownList("Employee_Gender", new List<SelectListItem>
                    {
                       new SelectListItem { Text="Male",Value="Male"},
                       new SelectListItem { Text="FeMale",Value="FeMale"}
                    }, "-- Select Gender --", htmlAttributes: new { @class = "form-control" })*@
                @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>

In _EditEmp.cshtml add the script as shown below
  

@model MVC_AccountPopUp.ViewModels.EmployeeViewModel

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

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

    <div class="modal-body">
        <div class="form-horizontal">
            @Html.HiddenFor(m => m.Employee.ID)

            <div class="form-group">
                @Html.LabelFor(m => m.Employee.FirstName, 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)
                </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.DropDownList("Employee_Gender", new List<SelectListItem>
                    {
                       new SelectListItem { Text="Male",Value="Male"},
                       new SelectListItem { Text="FeMale",Value="FeMale"}
                    }, "-- Select Gender --", htmlAttributes: new { @class = "form-control" })*@
                @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="Update" id="btnSubmit" />
    </div>
}

<script>
    $(document).ready(function () {
        $.validator.unobtrusive.parse('#EditEmp');
        $("#btnSubmit").click(function () {
            if (!$("#EditEmp").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>

5 comments:

  1. Sir,i am catching error inside my controller action method which contain try catch block.Actually my code is throwing exception and i want to show that.
    So how can i show this error message using toastr?

    ReplyDelete
    Replies
    1. Hi Rahul, Sorry for the delay.
      Use this in catch block

      return new JsonResult
      {
      Data = new { ErrorMessage = ex.Message, Success = false },
      ContentEncoding = System.Text.Encoding.UTF8,
      JsonRequestBehavior = JsonRequestBehavior.DenyGet
      };

      and in modalForms.js ==> bindForm() method ==> else part
      replace with the below code.

      $("#MyModal").modal('show');
      toastr.error(result.ErrorMessage);

      Delete
    2. Updated Source Code for crate.

      Delete
  2. Replies
    1. Thank you Hoi Tran Minh for visiting.
      Let me know if any errors, So that I rectify and update.
      It will be helpful for others.

      Delete