Monday, 10 June 2019

CRUD Opereaion in MVC , data table & modal popup.











VIEW MODEL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace WebApplication1.Models
{
    public class EMPVM1
    {
      public EMPVM1()
        {
            HOBBY = new List<SelectListItem>();
            LINTEREST = new List<SelectListItem>();
            LCOUNTRY = new List<SelectListItem>();
            LSTATE = new List<SelectListItem>();

        }
        [Required(ErrorMessage ="Eid should not be blank.")]
        public int? EID { get; set; }
        [Required(ErrorMessage = "Name should not be blank.")]
        public string NAME { get; set; }
        [Required(ErrorMessage = "Address should not be blank.")]
        [DataType(DataType.MultilineText)]
        public string ADDRESS { get; set; }
        [Required(ErrorMessage = "Password should not be blank.")]
        [DataType(DataType.Password)]
[StringLength(8,MinimumLength =6,ErrorMessage ="Password length between 6 to 8 charecter long.")]
        [Remote("CheackPwd","Emps",ErrorMessage ="This password alredy exist.")]
        public string PASSWORD { get; set; }
        [Required(ErrorMessage = "Confirm password should not be blank.")]
        [DataType(DataType.Password)]
        [DisplayName("CONFIRM PASSWORD")]
        [System.ComponentModel.DataAnnotations.Compare("PASSWORD", ErrorMessage ="Password and confrim password must be same.")]
        public string CPASSWORD { get; set; }
        [Required(ErrorMessage = "Please select a gender.")]
        public string GENDER { get; set; }
        [Required(ErrorMessage = "Salary should not be blank.")]
        [Range(5000,500000,ErrorMessage ="Salary range between from 5000 to 500000.")]
        public decimal? SALARY { get; set; }
        [Required(ErrorMessage = "Email should not be blank.")]
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage ="Invalid email.")]
        public string EMAIL { get; set; }
        [Required(ErrorMessage = "DOJ should not be blank.")]
        public DateTime? DOJ { get; set; }
        [Required(ErrorMessage ="Please select a country.")]
        [Coustomvalidation2(ErrorMessage ="Please select a hobby.")]
        public List<SelectListItem> HOBBY { get; set; }
        public List<SelectListItem> LINTEREST { get; set; }
        [Coustomvalidation3(ErrorMessage = "Please select a interest.")]
        public List<string> INTEREST { get; set; }
        [Required(ErrorMessage ="Please select a country.")]
        [DisplayName("COUNTRY")]
        public int? CID { get; set; }
        public List<SelectListItem> LCOUNTRY { get; set; }
        [Required(ErrorMessage = "Please select a state.")]
        [DisplayName("STATE")]
        public int? SID { get; set; }
        public List<SelectListItem> LSTATE { get; set; }

    }
    public class Coustomvalidation2 : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            return ((List<SelectListItem>)value).Count(x => x.Selected == true) > 0;
        }
    }
    public class Coustomvalidation3 : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            return ((List<string>)value).Count > 0;
        }
    }



}



CONTROLLER :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class EmpsController : Controller
    {
        // GET: Emps
        public ActionResult Index()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return View(obj.EMPs.ToList());
            }
        }
        public JsonResult Fillddl(int CID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return Json(obj.STATEs.Where(m => m.CID == CID).ToList(), JsonRequestBehavior.AllowGet);
            }
        }
        public PartialViewResult Openpop()
        {
            EMPVM1 vm = new EMPVM1();
            using (Database1Entities obj = new Database1Entities())
            {
                vm.HOBBY = obj.HOBBies.Select(x => new SelectListItem { Value = x.HID.ToString(), Text = x.HNAME, Selected = false }).ToList();
                vm.LINTEREST = obj.INTERESTs.Select(x => new SelectListItem { Value = x.IID.ToString(), Text = x.INAMEE }).ToList();
                vm.LCOUNTRY = obj.COUNTRies.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList();
                vm.LSTATE = new List<SelectListItem>();
            }
                return PartialView("PVCreate1", vm);
        }
        public JsonResult CheackPwd(string PASSWORD)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                if (PASSWORD == null)
                    return Json(false, JsonRequestBehavior.AllowGet);
                return Json(!obj.EMPs.Any(x => x.PASSWORD.ToLower() == PASSWORD), JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult Save(EMPVM1 vm)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp = new EMP();
                emp.EID = vm.EID ?? 0;
                emp.NAME = vm.NAME;
                emp.ADDRESS = vm.ADDRESS;
                emp.PASSWORD = vm.PASSWORD;
                emp.GENDER = vm.GENDER;
                emp.SALARY = vm.SALARY;
                emp.EMAIL = vm.EMAIL;
                emp.DOJ = vm.DOJ;
                emp.CID = vm.CID;
                emp.SID = vm.SID;
                obj.Entry(emp).State = EntityState.Added;
                obj.SaveChanges();
                obj.HOBBYMAPs.AddRange(vm.HOBBY.Where(p => p.Selected == true).Select(x => new HOBBYMAP { EID = vm.EID, HID = Convert.ToInt32(x.Value) }));
                obj.SaveChanges();
                obj.INTERESTMAPs.AddRange(vm.INTEREST.Select(x => new INTERESTMAP { EID = vm.EID, IID = Convert.ToInt32(x) }).ToList());
                obj.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        public PartialViewResult Openpar(int EID)
        {
           
            EMPVM1 vm = new EMPVM1();
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp = obj.EMPs.Find(EID);
                vm.EID = emp.EID;
                vm.NAME = emp.NAME;
                vm.ADDRESS = emp.ADDRESS;
                vm.GENDER = emp.GENDER;
                vm.SALARY = emp.SALARY;
                vm.EMAIL = emp.EMAIL;
                vm.DOJ = vm.DOJ;
                vm.CID = vm.CID;
                vm.SID = vm.SID;
                List<SelectListItem> lst = new List<SelectListItem>();
                int mark;
                foreach (HOBBY hb in obj.HOBBies)
                {
                    mark = 0;
                    foreach (HOBBYMAP hm in obj.HOBBYMAPs.Where(m=>m.EID==EID))
                    {
                        if (hb.HID == hm.HID)
                        {
                            mark = 1;
                            break;
                        }
                    }
                    if (mark == 1)
                        lst.Add(new SelectListItem { Value=hb.HID.ToString(), Text=hb.HNAME,Selected=true });
                    else
                        lst.Add(new SelectListItem { Value = hb.HID.ToString(), Text = hb.HNAME, Selected = false });
                }
                vm.HOBBY = lst;
                List<SelectListItem> lst1 = new List<SelectListItem>();
                foreach (INTEREST ints in obj.INTERESTs)
                {
                    mark = 0;
                    foreach (INTERESTMAP im in obj.INTERESTMAPs.Where(p => p.EID == vm.EID))
                    {
                        if (ints.IID == im.IID)
                        {
                            mark = 1;
                            break;
                        }
                    }
                    if (mark == 1)
                        lst1.Add(new SelectListItem { Value=ints.IID.ToString(), Text=ints.INAMEE, Selected=true });
                    else
                        lst1.Add(new SelectListItem { Value = ints.IID.ToString(), Text = ints.INAMEE, Selected = false });
                }
                vm.LINTEREST = lst1;
                vm.DOJ = emp.DOJ;
                vm.CID = emp.CID;
                vm.SID = emp.SID;
                vm.LCOUNTRY = obj.COUNTRies.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList();
                vm.LSTATE = obj.STATEs.Where(p=>p.CID==vm.CID).Select(x => new SelectListItem { Value = x.SID.ToString(), Text = x.SNAME }).ToList();
            }
            return PartialView("PVEdit", vm);
        }
        public ActionResult Edit(EMPVM1 vm)
        {
            ModelState.Remove("PASSWORD");
            ModelState.Remove("CPASSWORD");
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp = obj.EMPs.Find(vm.EID);
                emp.NAME = vm.NAME;
                emp.ADDRESS = vm.ADDRESS;
                emp.GENDER = vm.GENDER;
                emp.SALARY = vm.SALARY;
                emp.EMAIL = vm.EMAIL;
                emp.DOJ = vm.DOJ;
                emp.CID = vm.CID;
                emp.SID = vm.SID;
                obj.Entry(emp).State = EntityState.Modified;
                obj.SaveChanges();
                obj.HOBBYMAPs.RemoveRange(obj.HOBBYMAPs.Where(x => x.EID == vm.EID));
                obj.SaveChanges();
                obj.HOBBYMAPs.AddRange(vm.HOBBY.Where(p => p.Selected == true).Select(x => new HOBBYMAP { EID = vm.EID, HID = Convert.ToInt32(x.Value) }));
                obj.SaveChanges();
                obj.INTERESTMAPs.RemoveRange(obj.INTERESTMAPs.Where(p => p.EID == vm.EID));
                obj.SaveChanges();
                obj.INTERESTMAPs.AddRange(vm.INTEREST.Select(x => new INTERESTMAP { EID = vm.EID, IID = Convert.ToInt32(x) }).ToList());
                obj.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        public JsonResult Delete(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp = obj.EMPs.Find(EID);
                obj.Entry(emp).State = EntityState.Deleted;
                obj.SaveChanges();
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }


    }
}

Index view

@model IEnumerable<WebApplication1.Models.EMP>

@{
    ViewBag.Title = "Index";
    Layout = null;
}


<br />
<p>
    <input type="button" value="Add New" class="btn btn-primary" id="btnadd" />
</p>
<table class="table" id="tb">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ADDRESS)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PASSWORD)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GENDER)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SALARY)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EMAIL)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.DOJ)
            </th>
            <th></th>
        </tr>
    </thead>

    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.EID)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.NAME)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ADDRESS)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.PASSWORD)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.GENDER)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CID)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.SID)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.SALARY)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EMAIL)
                </td>
                <td>
                    @{
                                string s = string.Format("{0:dd-MMM-yy}", item.DOJ);
                     }
                     @s
                </td>
                <td>
                    <a class="edit">Edit</a> |
                    <a class="del">Delete</a>
                </td>
            </tr>
        }
    </tbody>

</table>
<div id="dmldv"></div>
<div id="delForm" style="display:none">
    <h1>Do you want to delete it ?</h1>
</div>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.dataTables.min.css" rel="stylesheet" />
<link href="~/Content/jquery.dataTables_themeroller.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
    var createMode = $("#dmldv").dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        show: { effect: 'blind', speed: 1000 },
        hide: { effect: 'blind', speed: 1000 },
        title: "Add New"
    });
    var Delform = $("#delForm");
    $(function () {
        $('#tb').on("click", ".edit", function () {
            $.ajax({
                "url": "@Url.Action("Openpar", "Emps")",
                type: 'Get',
                datatype: 'json',
                cache: false,
                data: { EID: $(this).closest("tr").find("td:eq(0)").text() },
                success: function (data) {
                    createMode.dialog("open");
                    createMode.empty().append(data);
                },
                error: function (t) {
                    alert(t.responseText);
                }
            });



        });
        $('#tb').on("click", ".del", function () {

            var id = $(this).closest("tr").find("td:first").text();
            Delform.dialog({
                autoOpen: false,
                modal: true,
                width: 550,
                title: "Delete",
                show: { effect: 'blind', speed: 1000 },
                hide: { effect: 'blind', speed: 1000 },

                buttons: {
                    Yes: function () {

                        $.ajax({
                            "url": "/Emps/Delete",
                            type: 'Get',
                            datatype: 'json',
                            cache: false,
                            data: { EID: id },
                            success: function (Data) {
                                Delform.dialog("close");
                                window.location.reload(true);

                            },
                            error: function (t) {
                                alert(t.responseText);
                            }
                        });


                    },
                    No: function () {
                        Delform.dialog("close");
                    }

                }

            });

            Delform.dialog("open");

        });
        $('#btnadd').click(function () {
            $.ajax({
                "url": "/Emps/Openpop",
                type: 'Get',
                datatype: 'json',
                cache: false,
                success: function (data) {
                    createMode.dialog("open");
                    createMode.empty().append(data);
                },
                error: function (t) {
                    alert(t.responseText);
                }
            });
        });

        var table = $("#tb").DataTable({
            "order": [[0, "asc"]],
            "lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]],
            "scroller": true,
            "orderClasses": false,
        })
    })
</script>


Create partial view :

@model WebApplication1.Models.EMPVM1

@using (Html.BeginForm("Save","Emps",FormMethod.Post))
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.EID, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.EID, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.EID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.NAME, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.NAME, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.NAME, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ADDRESS, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ADDRESS, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ADDRESS, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PASSWORD, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.PASSWORD, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PASSWORD, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CPASSWORD, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CPASSWORD, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CPASSWORD, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.GENDER, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.RadioButtonFor(model => model.GENDER, "Male", new { htmlAttributes = new { @class = "form-control" } })Male
            @Html.RadioButtonFor(model => model.GENDER, "Female", new { htmlAttributes = new { @class = "form-control" } })Female
            @Html.ValidationMessageFor(model => model.GENDER, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.HOBBY, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @{
                for (int i = 0; i < Model.HOBBY.Count; i++)
                {
                    @Html.CheckBoxFor(x => Model.HOBBY[i].Selected)
                    @Html.DisplayFor(x => Model.HOBBY[i].Text)
                    @Html.HiddenFor(x => Model.HOBBY[i].Value)
                    @Html.HiddenFor(x => Model.HOBBY[i].Text)@:&nbsp;

                }
            }
            @Html.ValidationMessageFor(model => model.HOBBY, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        @Html.LabelFor(model => model.SALARY, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.SALARY, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.SALARY, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.EMAIL, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.EMAIL, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.EMAIL, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DOJ, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DOJ, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DOJ, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.INTEREST, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.ListBoxFor(model => model.INTEREST, Model.LINTEREST, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.INTEREST, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CID, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.CID, Model.LCOUNTRY, "Select", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.SID, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.SID, Model.LSTATE, "Select", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.SID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
    $(function () {

        $('#DOJ').datepicker();
        $('#CID').change(function () {
            $('#SID').empty();
            $('#SID').append("<option>Select</option>");
            $.ajax({
                url: '/Emps/Fillddl',
                data: { CID: $(this).val() },
                success: function (data) {
                    $.each(data, function (i, v) {
                        $('#SID').append("<option value="+v.SID+">"+v.SNAME+"</option>");
                    });
                   
                }
            });
        });
    });
</script>

Edit partial view :

@model WebApplication1.Models.EMPVM1

@using (Html.BeginForm("Edit", "Emps", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.EID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.HiddenFor(m=>m.EID)
                @Html.DisplayFor(model => model.EID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.NAME, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.NAME, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.NAME, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ADDRESS, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ADDRESS, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ADDRESS, "", new { @class = "text-danger" })
            </div>
        </div>

       

        <div class="form-group">
            @Html.LabelFor(model => model.GENDER, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.RadioButtonFor(model => model.GENDER, "Male", new { htmlAttributes = new { @class = "form-control" } })Male
                @Html.RadioButtonFor(model => model.GENDER, "Female", new { htmlAttributes = new { @class = "form-control" } })Female
                @Html.ValidationMessageFor(model => model.GENDER, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.HOBBY, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @{
                    for (int i = 0; i < Model.HOBBY.Count; i++)
                    {
                        @Html.CheckBoxFor(x => Model.HOBBY[i].Selected)
                        @Html.DisplayFor(x => Model.HOBBY[i].Text)
                        @Html.HiddenFor(x => Model.HOBBY[i].Value)
                        @Html.HiddenFor(x => Model.HOBBY[i].Text)@:&nbsp;

                    }
                }
                @Html.ValidationMessageFor(model => model.HOBBY, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            @Html.LabelFor(model => model.SALARY, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SALARY, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SALARY, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.EMAIL, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EMAIL, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EMAIL, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DOJ, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DOJ, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DOJ, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.INTEREST, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.ListBoxFor(model => model.INTEREST, Model.LINTEREST, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.INTEREST, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CID, Model.LCOUNTRY, "Select", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.CID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.SID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SID, Model.LSTATE, "Select", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.SID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script type="text/javascript">
    $(function () {
//$("#PASSWORD").rules("remove", "required")
//$("#CPASSWORD").rules("remove", "required")   
//$("#CPASSWORD").rules("add", "required")   
   
  $('#DOJ').datepicker();
        $('#CID').change(function () {
            $('#SID').empty();
            $('#SID').append("<option>Select</option>");
            $.ajax({
                url: '/Emps/Fillddl',
                data: { CID: $(this).val() },
                success: function (data) {
                    $.each(data, function (i, v) {
                        $('#SID').append("<option value="+v.SID+">"+v.SNAME+"</option>");
                    });

                }
            });
        });
    });
</script>



Monday, 4 March 2019

CRUD operation using webapi2, angular6 & ngx-bootstrap modal & datepicker




Web api :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication5.Models;

namespace WebApplication5.Controllers
{
    [RoutePrefix("api/Pgs")]
    public class PgsController : ApiController
    {
        [HttpGet]
        [Route("Countries")]
        public IHttpActionResult Countries()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.COUNTRies.ToList());
                }
            }
            catch(Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("State/{CID:int}")]
        public IHttpActionResult State(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("PGS")]
        public IHttpActionResult PGS()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.PGS1.ToList());
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("Gets/{EID:int}")]
        public IHttpActionResult Gets(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.PGS1.Find(EID));
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        [Route("Get/{EID:int}",Name ="PG1")]
        public IHttpActionResult Get(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.PGS1.Find(EID));
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(PG1 vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(vm).State = EntityState.Added;
                    obj.SaveChanges();
                    return Created(Url.Link("PG1", new { EID = vm.EID }),"Data Saved.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpPut]
        [Route("Update")]
        public IHttpActionResult Update(PG1 vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(vm).State = EntityState.Modified;
                    obj.SaveChanges();
                    return Ok("Data Updated.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpDelete]
        [Route("Delete/{EID:int}")]
        public IHttpActionResult Delete(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    obj.Entry(obj.PGS1.Find(EID)).State = EntityState.Deleted;
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

    }
}

First you install ngx-bootstrap for modal popup & datepicker using below command

npm install ngx-bootstrap@2.0.5 --save
or
npm install ngx-bootstrap@3.0.1 --save

After that you inject in app.module file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CreateempComponent } from './emp/createemp.component';
import { FormsModule } from '@angular/forms';
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker';
import { ModalModule } from 'ngx-bootstrap';
import { EmpServices } from './emp/emp.services';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent,
    CreateempComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    BsDatepickerModule.forRoot(),
    ModalModule.forRoot(),
    HttpClientModule
  ],
  providers: [EmpServices],
  bootstrap: [AppComponent]
})
export class AppModule { }






Angular Model :

export class COUNTRY {
    CID: number;
    CNAME: string;
}
export class STATE {
    SID: number;
    SNAME: string;
    CID: number;
}
export class IPGS {
    EID: number;
    NAME: string;
    DOJ: Date;
    CID: number;
    SID: number;
}

Angular Service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { IPGS, COUNTRY, STATE } from './emp.model';
import 'rxjs/add/operator/toPromise';



@Injectable()
export class EmpServices {
    baseUrl = 'http://localhost:2813/api/Pgs';
    constructor(private http: HttpClient) {
    }
    Getc(): Promise<COUNTRY[]> {
        return this.http.get<COUNTRY[]>(`${this.baseUrl}/${'Countries'}`)
        .toPromise();
    }
    Gets(cid: number): Promise<STATE[]> {
        return this.http.get<STATE[]>(`${this.baseUrl}/${'State'}/${cid}`)
        .toPromise();
    }
    Get(eid: number): Promise<IPGS> {
        return this.http.get<IPGS>(`${this.baseUrl}/${'Gets'}/${eid}`)
        .toPromise();
    }
    Getp(): Promise<IPGS[]> {
        return this.http.get<IPGS[]>(`${this.baseUrl}/${'PGS'}`)
        .toPromise();
    }
    Save(vm: IPGS): Promise<string>  {
        return this.http.post<string>(`${this.baseUrl}/${'Save'}`
        , JSON.stringify(vm)
        , { headers : new HttpHeaders({'Content-Type': 'application/json' })}
        ).toPromise();
    }
    Update(vm: IPGS): Promise<string>  {
        return this.http.put<string>(`${this.baseUrl}/${'Update'}`
        , JSON.stringify(vm)
        , { headers : new HttpHeaders({'Content-Type': 'application/json' })}
        ).toPromise();
    }
    Delete(eid: number): Promise<string>  {
        return this.http.delete<string>(`${this.baseUrl}/${'Delete'}/${eid}`
        , { headers : new HttpHeaders({'Content-Type': 'application/json' })}
        ).toPromise();
    }
}

Angular Component :

import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import {IPGS, COUNTRY, STATE} from './emp.model';
import { EmpServices } from './emp.services';
import { NgForm } from '@angular/forms';


@Component({
  selector: 'app-createemp',
  templateUrl: './createemp.component.html',
  styleUrls: ['./createemp.component.css']
})
export class CreateempComponent implements OnInit {
  modalRef: BsModalRef;
  PGS: IPGS;
  listc: COUNTRY[];
  lists: STATE[];
  list: IPGS[];
  eid: number;
  header: string;
  constructor(private modalService: BsModalService, private es: EmpServices) { }

  ngOnInit() {
    this.CLR();
    this.es.Getc().then(data => this.listc = data);
    this.fill();
  }
  openModal(template: TemplateRef<any>) {
    this.header = 'Add New';
    this.CLR();
    this.modalRef = this.modalService.show(template);
  }
  fillddl(): void {
    this.fx(this.PGS.CID);
}
fx(cid: number): void {
this.es.Gets(cid).then(data => {
  this.lists = data;
});
}
save(isValid: boolean): void {
if (isValid === false) {
  if (this.eid === undefined) {
    this.es.Save(this.PGS).then(data => {
      alert(data);
      this.fill();
      this.modalService.hide(1);
    });
  } else {
    this.es.Update(this.PGS).then(data => {
      alert(data);
      this.fill();
    });
  }
  this.modalService.hide(1);
}
}
edit(id: number, template: TemplateRef<any>): void {
  this.header = 'Edit';
  this.eid = id;
  this.es.Get(id).then(data =>  {
      this.PGS = data;
      const dt = new Date(this.PGS.DOJ);
      const dt1 = (dt.getMonth() + 1) + '/' + dt.getDate() + '/' + dt.getFullYear();
      this.PGS.DOJ = new Date(dt1);
      this.fx(this.PGS.CID);
    });
  this.modalRef = this.modalService.show(template);
}
del(id: number, template1: TemplateRef<any>): void {
  this.eid = id;
  this.modalRef = this.modalService.show(template1);
}
yes(): void {
  this.es.Delete(this.eid).then(data => {
    alert(data);
    this.fill();
    this.modalService.hide(1);
  });
}
fill(): void {
  this.es.Getp().then(data => this.list = data);
}
reset(): void {
  this.CLR();
}
  CLR(): void {
    this.PGS = {
      EID: null,
      NAME: null,
      DOJ: null,
      CID: null,
      SID: null
    };
    this.eid = undefined;
  }
}


Angular Html :

       <div class="row">
    <button type="button" class="btn btn-primary" (click)="openModal(template)">Add New</button>
</div><br>
<div class="row">
    <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
        <thead class="bg bg-primary">
            <tr>
                <th>SL NO.</th>
                <th>NAME</th>
                <th>DOJ</th>
                <th>ACTION</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let c of list;let i=index">
                <td>{{i+1}}</td>
                <td>{{c.NAME}}</td>
                <td>{{c.DOJ|date:'dd-MMM-yyyy'}}</td>
                <td>
                        <button type="button" style="width:70px" class="btn btn-primary" (click)="edit(c.EID,template)">Edit</button> |
                     <button type="button" (click)="del(c.EID,template1)" style="width:70px" class="btn btn-primary" >Delete</button>
                
                </td>
            </tr>
        </tbody>
    </table>
</div>
 
<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">{{header}}</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <form class="form-horizontal" #frmEmp="ngForm">
      <div class="form-group" [class.has-error]="EID.invalid && EID.touched" [class.has-success]="EID.valid">
          <label class="control-label col-lg-2">EID</label>
          <div class="col-lg-6">
              <input type="text" class="form-control" name="EID" #EID="ngModel" [(ngModel)]="PGS.EID" required />
          </div>
          <span class="help-block" *ngIf="EID.invalid && EID.touched">Eid should not be blank.</span>
      </div>
      <div class="form-group" [class.has-error]="NAME.invalid && NAME.touched" [class.has-success]="NAME.valid">
          <label class="control-label col-lg-2">NAME</label>
          <div class="col-lg-6">
              <input type="text" class="form-control" name="NAME" #NAME="ngModel" [(ngModel)]="PGS.NAME" required />
          </div>
          <span class="help-block" *ngIf="NAME.invalid && NAME.touched">Name should not be blank.</span>
      </div>
      <div class="form-group" [class.has-error]="DOB.invalid && DOB.touched" [class.has-success]="DOB.valid">
          <label class="control-label col-lg-2">DOB</label>
          <div class="col-lg-6">
              <input type="text"  bsDatepicker class="form-control"  name="DOB" #DOB="ngModel" [(ngModel)]="PGS.DOJ" required />
          </div>
          <span class="help-block" *ngIf="DOB.invalid && DOB.touched">Name should not be blank.</span>
      </div>
      <div class="form-group" [class.has-error]="CID.invalid && CID.touched" [class.has-success]="CID.valid">
        <label class="control-label col-lg-2">COUNTRY</label>
        <div class="col-lg-6">
            <select (change)="fillddl()"  class="form-control" name="CID" #CID="ngModel" [(ngModel)]="PGS.CID" required >
                <option [ngValue]="null">Select</option>
                <option *ngFor="let c of listc" [value]="c.CID">{{c.CNAME}}</option>
            </select>
        </div>
        <span class="help-block" *ngIf="CID.invalid && CID.touched">Please select a country.</span>
    </div>
    <div class="form-group" [class.has-error]="SID.invalid && SID.touched" [class.has-success]="SID.valid">
        <label class="control-label col-lg-2">STATE</label>
        <div class="col-lg-6">
            <select class="form-control" name="SID" #SID="ngModel" [(ngModel)]="PGS.SID" required>
                <option [ngValue]="null">Select</option>
                <option *ngFor="let c of lists" [value]="c.SID">{{c.SNAME}}</option>
            </select>
        </div>
        <span class="help-block" *ngIf="SID.invalid && SID.touched">Please select a state.</span>
    </div>
    </form>
    
  </div>
  <div class="modal-footer">
      <input type="button" class="btn btn-primary" value="Submit" style="width:80px" (click)="save(frmEmp.invalid)" />
      <input type="button" class="btn btn-primary" value="Reset" style="width:80px" (click)="reset()" />
      <input type="button" class="btn btn-primary" value="Close" style="width:80px" (click)="modalRef.hide()" />
    
  </div>
</ng-template>

<ng-template #template1>
    <div class="modal-header">
      <h4 class="modal-title pull-left">Alert Message</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <h2>Do you want to delete it ?</h2>
    </div>
    <div class="modal-footer">
        <input type="button" class="btn btn-primary" value="Yes" style="width:80px" (click)="yes()" />
        <input type="button" class="btn btn-primary" value="No" style="width:80px" (click)="modalRef.hide()" />
    </div>
</ng-template>