Saturday, 24 July 2021

Dynamic Page in MVC

 




View Model :

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

namespace SMS.ViewModels
{
    public class UserroleVM:BaseVM
    {
        public int URID { get; set; }
        public int UID { get; set; }
        [Required(ErrorMessage = "Please select user name.")]
        [Display(Name = "User Name")]
        public string UNAME { get; set; }
        [Required(ErrorMessage = "Please select role.")]
        [Display(Name = "Role")]
        public int RID { get; set; }
        public string RNAME { get; set; }
        public List<SelectListItem> RLIST { get; set; }
        [Required(ErrorMessage = "Please select menu.")]
        [Display(Name = "Menu")]
        public List<int> MID { get; set; }
        public List<SelectListItem> MLIST { get; set; }
        public string MNAME { get; set; }
        public string PNAME { get; set; }
        public List<Pagedetails> PAGELIST { get; set; }
        public UserroleVM()
        {
            RLIST = new List<SelectListItem>();
            MID = new List<int>();
            MLIST = new List<SelectListItem>();
            PAGELIST = new List<Pagedetails>();
        }
        public void fillddl(List<SelectListItem> rl, List<SelectListItem> ml)
        {
            RLIST = rl;
            MLIST = ml;
        }

    }
    public class Pagedetails
    {
        public int PID { get; set; }
        public string PNAME { get; set; }
        public bool ADD { get; set; }
        public bool EDIT { get; set; }
        public bool DELETE { get; set; }
        public bool VIEW { get; set; }
    }
}


Controller:


using SMS.Models;
using SMS.ViewModels;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace SMS.Controllers
{
    public class UserrolesController : Controller
    {
        #region variable
        private static string message = string.Empty;
        #endregion
        [HttpGet]
        public async Task<ActionResult> Index()
        {
            using (AppDbContext obj = new AppDbContext())
            {
                var data1 = await obj.Userroles.ToListAsync();
                List<UserroleVM> attendancegrideviews = (from x in data1
                                                                  join y in obj.Users
                                                                  on x.UID equals y.UID
                                                                  join z in obj.Roles
                                                                  on x.RID equals z.RID
                                                                  select new UserroleVM()
                                                                  {
                                                                      URID = x.RUID,
                                                                      UNAME = y.UNAME,
                                                                      RNAME = z.RNAME,
                                                                      MNAME =string.Join(",", obj.Menus.Where(a => obj.Userrolemenus.Where(p => p.RUID == x.RUID).Select(q => q.MID).Contains(a.MID)).Select(b=>b.MNAME.ToString()).ToList())
                                                                  }).ToList();
                return View(attendancegrideviews);
            }
        }
        [HttpGet]
        public async Task<ActionResult> Create()
        {
            using (AppDbContext obj = new AppDbContext())
            {
                UserroleVM attendanceVM = new UserroleVM();
                attendanceVM.fillddl(await obj.Roles.Select(m => new SelectListItem { Value = m.RID.ToString(), Text = m.RNAME }).ToListAsync(), await obj.Menus.Select(n => new SelectListItem { Value = n.MID.ToString(), Text = n.MNAME }).ToListAsync());
                List<Pagedetails> lst = new List<Pagedetails>();
                attendanceVM.PAGELIST = lst;
                attendanceVM.URID = 0;
                if (!string.IsNullOrEmpty(message))
                {
                    attendanceVM.Message = message;
                    message = null;
                }
                return View(attendanceVM);
            }
        }
        [HttpPost]
        [ValidateAntiForgeryToken()]
        public async Task<ActionResult> Create(UserroleVM attendanceVM)
        {
            if (ModelState.IsValid)
            {
                using (AppDbContext obj = new AppDbContext())
                {
                    Userrole incomehead = new Userrole();
                    if (attendanceVM.URID == 0)
                    {
                        incomehead.UID = attendanceVM.UID;
                        incomehead.RID = attendanceVM.RID;
                        obj.Entry(incomehead).State = EntityState.Added;
                        await obj.SaveChangesAsync();
                        obj.Userrolemenus.AddRange(attendanceVM.MID.Select(x=>new Userrolemenu { RUID=incomehead.RUID, MID=x }));
                        await obj.SaveChangesAsync();
                        obj.Userrolepages.AddRange(attendanceVM.PAGELIST.Select(x => new Userrolepage { RUID = incomehead.RUID, PID=x.PID,ADD=x.ADD, EDIT=x.EDIT, DELETE=x.DELETE, VIEW=x.VIEW }));
                        await obj.SaveChangesAsync();
                        message = "Data Saved Successfully.";
                    }
                    else
                    {
                        incomehead = obj.Userroles.Find(attendanceVM.URID);
                        incomehead.UID = attendanceVM.UID;
                        incomehead.RID = attendanceVM.RID;
                        obj.Entry(incomehead).State = EntityState.Modified;
                        await obj.SaveChangesAsync();
                        obj.Userrolemenus.RemoveRange(obj.Userrolemenus.Where(x=>x.RUID==incomehead.RUID));
                        await obj.SaveChangesAsync();
                        obj.Userrolemenus.AddRange(attendanceVM.MID.Select(x => new Userrolemenu { RUID = incomehead.RUID, MID = x }));
                        await obj.SaveChangesAsync();
                        obj.Userrolepages.RemoveRange(obj.Userrolepages.Where(x => x.RUID == incomehead.RUID));
                        await obj.SaveChangesAsync();
                        obj.Userrolepages.AddRange(attendanceVM.PAGELIST.Select(x => new Userrolepage { RUID = incomehead.RUID, PID = x.PID, ADD = x.ADD, EDIT = x.EDIT, DELETE = x.DELETE, VIEW = x.VIEW }));
                        await obj.SaveChangesAsync();
                        message = "Data Updated Successfully.";

                    }
                    return RedirectToAction("Create");
                }
            }
            return View(attendanceVM);
        }
        [HttpPost]
        public async Task<ActionResult> Create1(UserroleVM attendanceVM)
        {
            using (AppDbContext obj = new AppDbContext())
            {
                List<Pagedetails> lst =await (from m in  obj.Pages.Where(p=>attendanceVM.MID.Contains(p.MID))
                                             select new Pagedetails {PID=m.PID, PNAME=m.PNAME}).ToListAsync();
                attendanceVM.PAGELIST = lst;
                attendanceVM.UID = attendanceVM.UID;
                attendanceVM.UNAME = attendanceVM.UNAME;
                attendanceVM.fillddl(await obj.Roles.Select(m => new SelectListItem { Value = m.RID.ToString(), Text = m.RNAME }).ToListAsync(), await obj.Menus.Select(n => new SelectListItem { Value = n.MID.ToString(), Text = n.MNAME }).ToListAsync());
                attendanceVM.RID = attendanceVM.RID;
                attendanceVM.MID = attendanceVM.MID;
                attendanceVM.URID = attendanceVM.URID;
                return View("Create", attendanceVM);
            }
        }
        [HttpGet]
        public async Task<ActionResult> Edit(int id)
        {
            using (AppDbContext obj = new AppDbContext())
            {
                UserroleVM attendanceVM = new UserroleVM();
                Userrole av = obj.Userroles.Find(id);
                attendanceVM.UID = av.UID;
                attendanceVM.UNAME = obj.Users.SingleOrDefault(m=>m.UID==av.UID).UNAME;
                attendanceVM.fillddl(await obj.Roles.Select(m => new SelectListItem { Value = m.RID.ToString(), Text = m.RNAME }).ToListAsync(), await obj.Menus.Select(n => new SelectListItem { Value = n.MID.ToString(), Text = n.MNAME }).ToListAsync());
                attendanceVM.RID = av.RID;
                attendanceVM.MID = obj.Userrolemenus.Where(p => p.RUID == av.RUID).Select(x => x.MID).ToList();
                attendanceVM.URID = av.RUID;
                List<Pagedetails> lst = await (from m in obj.Pages.Where(p => attendanceVM.MID.Contains(p.MID))
                                               join n in obj.Userrolepages
                                               on m.PID equals n.PID
                                               select new Pagedetails { PID = m.PID, PNAME = m.PNAME, ADD=n.ADD,EDIT=n.EDIT,DELETE=n.DELETE,VIEW=n.VIEW }).ToListAsync();
                attendanceVM.PAGELIST = lst;
                return View("Create", attendanceVM);
            }
        }
        [HttpGet]
        public async Task<ActionResult> Delete(int id)
        {
            using (AppDbContext obj = new AppDbContext())
            {
                Userrole addmission = obj.Userroles.Find(id);
                obj.Entry(addmission).State = EntityState.Deleted;
                await obj.SaveChangesAsync();
                obj.Userrolemenus.RemoveRange(obj.Userrolemenus.Where(x => x.RUID == id));
                await obj.SaveChangesAsync();
                obj.Userrolepages.RemoveRange(obj.Userrolepages.Where(x => x.RUID == id));
                await obj.SaveChangesAsync();
                return RedirectToAction("Index");
            }
        }
        public async Task<PartialViewResult> Details(int id)
        {
            using (AppDbContext obj = new AppDbContext())
            {
                var data1 = await obj.Userroles.Where(m=>m.RUID==id).ToListAsync();
                UserroleVM attendancegrideviews = (from x in data1
                                                         join y in obj.Users
                                                         on x.UID equals y.UID
                                                         join z in obj.Roles
                                                         on x.RID equals z.RID
                                                         select new UserroleVM()
                                                         {
                                                             URID = x.RUID,
                                                             UNAME = y.UNAME,
                                                             RNAME = z.RNAME,
                                                             MNAME = string.Join(",", obj.Menus.Where(a => obj.Userrolemenus.Where(p => p.RUID == x.RUID).Select(q => q.MID).Contains(a.MID)).Select(b => b.MNAME.ToString()).ToList()),
                                                             PAGELIST = obj.Userrolepages.Where(g => g.RUID == x.RUID).Select(h => new Pagedetails
                                                             {
                                                                 PNAME = obj.Pages.FirstOrDefault(i => i.PID == h.PID).PNAME,
                                                                 ADD = h.ADD,
                                                                 EDIT = h.EDIT,
                                                                 DELETE = h.DELETE,
                                                                 VIEW = h.VIEW
                                                             }).ToList()
                                                         }).FirstOrDefault(m=>m.URID==id);
                return PartialView("DetailsPV", attendancegrideviews);
            }

        }
        [HttpPost]
        public ActionResult AutoComplete(string prefix)
        {
            using (AppDbContext obj = new AppDbContext())
            {
                return Json(obj.Users.Select(x => new { val = x.UID, label = x.UNAME }).ToList(), JsonRequestBehavior.AllowGet);
            }
        }
    }
}

Index View :

@model IEnumerable<SMS.ViewModels.UserroleVM>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Adminlayout.cshtml";
}

<p>
    @Html.ActionLink("Add New", "Create", null, new { @class = "btn btn-primary" })
</p>
<table class="table table-bordered table-hover table-responsive" id="tbc">
    <thead class="bg bg-primary">
        <tr>
            <th>
                ID
            </th>
            <th>
                User Name
            </th>
            <th>
                Role Name
            </th>
            <th>
                Menus Name
            </th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.URID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UNAME)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.RNAME)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MNAME)
            </td>
            <td>
                <a href="#"><span class="glyphicon glyphicon-eye-open view"></span></a> |
                <a href="@Url.Action("Edit","Userroles",new {id=item.URID })"><span class="glyphicon glyphicon-edit edit"></span></a> |
                <a href="#" onclick="confirmDelete('@Url.Content("~/Userroles/Delete/" + item.URID)')"><span class="glyphicon glyphicon-remove-circle del"></span></a>

            </td>
        </tr>
        }
    </tbody>
</table>
@Html.Partial("DeletePV")
<div class="modal fade" id="deleteModal1" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">User Access Details</h4>
            </div>
            <div class="modal-body bd">

            </div>
            <div class="modal-footer">
                <input type="button" value="Close" class="btn btn-primary focusedButton" data-dismiss="modal" style="width:80px" />
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">

    $(function () {

        var table = $("#tbc").DataTable({
            "order": [[0, "asc"]],
            "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            "scroller": true,
            "orderClasses": false,
        });
          $('.view').click(function () {
            var Id = $(this).closest("tr").find("td:first").text();
                $.ajax({
                    "url":  '@Url.Action("Details", "Userroles")',
                    type: 'Get',
                    datatype: 'json',
                    cache: false,
                    async: true,
                    data: {id:Id},
                    success: function (data) {
                        $('#deleteModal1').find('.bd').empty().append(data);
                        $('#deleteModal1').modal('show');
                    },
                    error: function (t) {
                        alert(t.responseText);
                    }
                });

        });

    });
</script>

Create View :

@model SMS.ViewModels.UserroleVM

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Adminlayout.cshtml";
}

<style>
    .top-buffer {
        margin-top: 2px;
    }
</style>
<h2>User Access Details</h2><br />

@using (Html.BeginForm("Create", "Userroles"))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="row">
            <div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">
                @Html.LabelFor(model => model.UNAME, htmlAttributes: new { @class = "control-label ", @autocomplete = "off" })
            </div>
            <div class="col-md-4 col-sm-4 col-lg-4 col-xl-4">
                @Html.HiddenFor(m => m.UID)
                @Html.HiddenFor(m => m.URID)
                @Html.EditorFor(model => model.UNAME, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UNAME, "", new { @class = "text-danger" })
            </div>
            <div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">
                @Html.LabelFor(model => model.RID, htmlAttributes: new { @class = "control-label " })
            </div>
            <div class="col-md-4 col-sm-4 col-lg-4 col-xl-4">

                @Html.DropDownListFor(model => model.RID, Model.RLIST, "Select", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.RID, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="row top-buffer">
            <div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">
                @Html.LabelFor(model => model.MID, htmlAttributes: new { @class = "control-label " })
            </div>
            <div class="col-md-4 col-sm-4 col-lg-4 col-xl-4">

                @Html.ListBoxFor(model => model.MID, Model.MLIST, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.MID, "", new { @class = "text-danger" })
            </div>
            <div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">
                <input type="button" value="Display" class="btn btn-primary" style="width:80px" id="btnd" />
            </div>
        </div>
        <div class="row top-buffer" style="overflow:auto; height:550px; border:#808080 1px solid">
            <table class="table table-bordered table-hover table-responsive" id="tbuser">
                <thead class="bg bg-primary">
                    <tr>

                        <th>
                            Page Name
                        </th>
                        <th>
                            Add
                        </th>
                        <th>
                            Edit
                        </th>
                        <th>
                            Delete
                        </th>
                        <th>
                            View
                        </th>
                    </tr>
                </thead>
                <tbody>
                    @{
                        if (Model.PAGELIST.Count == 0)
                        {
                            <tr><td colspan="5" style="text-align:center">No data available in table</td></tr>
                        }
                        for (int i = 0; i < Model.PAGELIST.Count; i++)
                        {
                            <tr>

                                <td>
                                    @Html.HiddenFor(modelItem => Model.PAGELIST[i].PID)
                                    @Html.DisplayFor(modelItem => Model.PAGELIST[i].PNAME)
                                    @Html.HiddenFor(modelItem => Model.PAGELIST[i].PNAME)
                                </td>
                                <td style="text-align:center">
                                    @Html.CheckBoxFor(modelItem => Model.PAGELIST[i].ADD, htmlAttributes: new { @class = "cbAdd" })
                                </td>
                                <td style="text-align:center">
                                    @Html.CheckBoxFor(modelItem => Model.PAGELIST[i].EDIT, htmlAttributes: new { @class = "cbEdit" })
                                </td>
                                <td style="text-align:center">
                                    @Html.CheckBoxFor(modelItem => Model.PAGELIST[i].DELETE, htmlAttributes: new { @class = "cbDelete" })
                                </td>
                                <td style="text-align:center">
                                    @Html.CheckBoxFor(modelItem => Model.PAGELIST[i].VIEW, htmlAttributes: new { @class = "cbView" })
                                </td>
                            </tr>
                        }
                    }
                </tbody>
            </table>
        </div>
        <div class="row top-buffer col-md-12 col-sm-12 col-lg-12 col-xl-12">
            <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">&nbsp;</div>
            <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6 pull-right">
                <input type="button" id="btns" value="Submit" class="btn btn-primary" style="width:80px" />
                @{
                    if (Model.URID == 0)
                    {

                        @Html.ActionLink("Reset", "Create", null, new { @class = "btn btn-default", @style = "width:80px" })
                    }
                    else
                    {
                        @Html.ActionLink("Reset", "Edit", new { id = Model.URID }, new { @class = "btn btn-default", @style = "width:80px" })
                    }
                }
            </div>
        </div>
    </div>
}
@{
    if (@Model.Message != null && @Model != null)
    {
        @Html.Partial("AlertPV", new SMS.ViewModels.Success() { Alertmessage = Model.Message })
    }
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
<div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" id="btnclose" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">Alert Message</h4>
            </div>
            <div class="modal-body">

            </div>
            <div class="modal-footer">

                <button type="button" id="btnOk" class="btn btn-primary focusedButton" data-dismiss="modal">Ok</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        $('#MID').chosen();
        $('#btnd').click(function () {
            if ($("form").valid()) {
                  $.ajax({
                    type: 'Post',
                    datatype: 'json',
                    cache: false,
                    async: true,
                    beforeSend: function () {
                        HoldOn.open({ theme: "sk-rect", content: '', message: 'Please wait for some time ...', backgroundColor: "#8C8C8C", textColor: "white" });
                        $("form").attr("action", "@Url.Action("Create1","Userroles")");
                        $("form").submit();
                      },
                      complete: function () {
                          HoldOn.close();
                      },
                      error: function (a, b, c) {
                          HoldOn.close();
                      }
                  });

            }
        });
        $('#btns').click(function () {
            if ($("form").valid()) {
                $.ajax({
                    type: 'Post',
                    datatype: 'json',
                    cache: false,
                    async: true,
                    beforeSend: function () {
                        HoldOn.open({ theme: "sk-rect", content: '', message: 'Please wait for some time ...', backgroundColor: "#8C8C8C", textColor: "white" });
                        $("form").submit();
                    },
                    complete: function () {
                        HoldOn.close();
                    },
                    error: function (a, b, c) {
                        HoldOn.close();
                    }
                });

            }
        });
        $('#btnOk,#btnclose').click(function () {

            var id =@Html.Raw(Json.Encode(Model.URID));
            if (id == 0) {
                window.location.href = "Index";
            } else {
                window.location.href = 0;
            }

        });
         var url = '@Url.Action("AutoComplete", "Userroles")';
        $('#UNAME').typeahead({
            hint: true,
            highlight: true,
            minLength: 1,
            source: function (request, response) {
                $.ajax({
                    url: url,
                    //data: "{ 'prefix': '" + request + "'}",
                    data: { prefix: request },
                    dataType: "json",
                    type: "POST",
                    //contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        //var data = JSON.parse(data1);
                        //console.log(data);
                        items = [];
                        map = {};
                        $.each(data, function (i, item) {
                            var id = item.val;
                            var name = item.label;
                            map[name] = { id: id, name: name };
                            items.push(name);
                            //items.push(item.name);
                        });
                        response(items);
                        $(".dropdown-menu").css("height", "auto");
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            updater: function (item) {
                $('#UID').val(map[item].id);
                return item;
            }
        });
    });
</script>

Details View :

@model SMS.ViewModels.UserroleVM
<div class="row">
    <div class="col-md-1 col-sm-1 col-lg-1 col-xl-1"><b>User:</b></div><div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">@Model.UNAME</div>
    <div class="col-md-1 col-sm-1 col-lg-1 col-xl-1"><b>Roles:</b></div><div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">&nbsp;&nbsp;@Model.RNAME</div>
    <div class="col-md-1 col-sm-1 col-lg-1 col-xl-1"><b>Menus:</b></div><div class="col-md-4 col-sm-4 col-lg-4 col-xl-4">@Model.MNAME</div>
</div><br />
<div class="row">
    <table class="table table-bordered table-hover table-responsive" id="tbc123" >
        <thead class="bg bg-primary">
            <tr>
                <th>Page Name</th>
                <th>Add</th>
                <th>Edit</th>
                <th>Delete</th>
                <th>View</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.PAGELIST)
            {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.PNAME)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ADD)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EDIT)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DELETE)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.VIEW)
                </td>
            </tr>
            }
        </tbody>
    </table>
</div>

<script type="text/javascript">
    $(function () {

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







Sunday, 4 October 2020

CRUD operations using Azure Function

 


using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

namespace FunctionApp1
{
    public static class Function1
    {
        public static readonly List<EMP> lst = new List<EMP>();
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function,"post", Route = "Save")] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Receive new employee request.");
            IActionResult returnValue = null;
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            try
            {
               if(emp!=null)
                {
                    lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
                    returnValue = new OkObjectResult("Data Saved.");
                }
               else
                {
                    returnValue = new StatusCodeResult(StatusCodes.Status400BadRequest);
                }

            }
            catch (Exception ex)
            {
                log.LogError($"Exception thrown: {ex.Message}");
                returnValue = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
            return returnValue;
        }
        [FunctionName("Function2")]
        public static async Task<IActionResult> Run2(
           [HttpTrigger(AuthorizationLevel.Function, "get", Route = "Gets")] HttpRequest req,
           ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            ////dynamic data = JsonConvert.DeserializeObject(requestBody);
            ////name = name ?? data?.name;

            ////string responseMessage = string.IsNullOrEmpty(name)
            ////    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            ////    : $"Hello, {name}. This HTTP triggered function executed successfully.";
            //EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            //lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
            return new OkObjectResult(lst);
        }
        [FunctionName("Function3")]
        public static async Task<IActionResult> Run3(
           [HttpTrigger(AuthorizationLevel.Function, "get", Route = "Get/{id:int}")] HttpRequest req,
           ILogger log,int id)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            ////dynamic data = JsonConvert.DeserializeObject(requestBody);
            ////name = name ?? data?.name;

            ////string responseMessage = string.IsNullOrEmpty(name)
            ////    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            ////    : $"Hello, {name}. This HTTP triggered function executed successfully.";
            //EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            //lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
            EMP emp = lst.FirstOrDefault(m => m.EID == id);
            return new OkObjectResult(emp);
        }
        [FunctionName("Function4")]
        public static async Task<IActionResult> Run4(
           [HttpTrigger(AuthorizationLevel.Function, "put", Route = "Update/{id:int}")] HttpRequest req,
           ILogger log,int id)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            //dynamic data = JsonConvert.DeserializeObject(requestBody);
            //name = name ?? data?.name;

            //string responseMessage = string.IsNullOrEmpty(name)
            //    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            //    : $"Hello, {name}. This HTTP triggered function executed successfully.";
            EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            lst.Remove(lst.FirstOrDefault(m=>m.EID==id));
            lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
            return new OkObjectResult("Data updated.");
        }
        [FunctionName("Function5")]
        public static async Task<IActionResult> Run5(
           [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "delete/{id:int}")] HttpRequest req,
           ILogger log, int id)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            ////dynamic data = JsonConvert.DeserializeObject(requestBody);
            ////name = name ?? data?.name;

            ////string responseMessage = string.IsNullOrEmpty(name)
            ////    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            ////    : $"Hello, {name}. This HTTP triggered function executed successfully.";
            //EMP emp = JsonConvert.DeserializeObject<EMP>(requestBody);
            //lst.Add(new EMP { EID = emp.EID, NAME = emp.NAME });
             lst.Remove(lst.FirstOrDefault(m=>m.EID==id));
            return new OkObjectResult("Data Deleted.");
        }
    }
}




how to add css for mobile

.text-panel{
 margin-top:-150px ;
 @include respond-below(medium) {
  margin-top:-10px;
}
}

Tuesday, 22 September 2020

CRUD operations using CORE(3.1) MVC,AutoMapper,Generic Repository & Dependency Injection, core EF code first approach ,Bootstrap modal popup,datepicker & multiselect drop down.


                                             


 using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using System.ComponentModel.DataAnnotations;


namespace WebApplication6.DAL

{

    public class Country

    {

        [Key]

        public int CID { get; set; }

        [MaxLength(50)]

        public string CNAME { get; set; }

    }

}

-
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class State
    {
        [Key]
        public int SID { get; set; }
        [MaxLength(50)]
        public string SNAME { get; set; }
        public int CID { get; set; }
        [ForeignKey("CID")]
        public virtual Country Country { get; set; }
    }
}
-
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class Hobby
    {
        [Key]
        public int HID { get; set; }
        [MaxLength(50)]
        public string HNAME { get; set; }
    }
}
-
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class Hobbymap
    {
        [Key]
        public int ID { get; set; }
        public int EID { get; set; }
        [ForeignKey("EID")]
        public virtual EMP EMP { get; set; }
        public int HID { get; set; }
        [ForeignKey("HID")]
        public virtual Hobby Hobby { get; set; }
    }
}
-
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class AppDbContext:DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }
        public DbSet<Country> Countries { get; set; }
        public DbSet<State> States { get; set; }
        public DbSet<Hobby> Hobbies { get; set; }

        public DbSet<Hobbymap> Hobbymaps { get; set; }
        public DbSet<EMP> EMPs { get; set; }
        public DbSet<DEPT> Depts { get; set; }
        public DbSet<Test> Tests { get; set; }
        public DbSet<Newemp> Newemps { get; set; }
        public DbSet<Hobbym> Hobbyms { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Country>().HasData(new Country { CID = 1, CNAME = "X" }, new Country { CID = 2, CNAME = "Y" }, new Country { CID = 3, CNAME = "Z" });
            modelBuilder.Entity<Hobby>().HasData(new Hobby { HID = 1, HNAME = "Cricket" }, new Hobby { HID = 2, HNAME = "Football" }, new Hobby { HID = 3, HNAME = "Baseball" }, new Hobby { HID = 4, HNAME = "Hockey" });
            modelBuilder.Entity<State>().HasData(new State { SID = 1, SNAME = "A", CID = 1 }, new State { SID = 2, SNAME = "B", CID = 1 }, new State { SID = 3, SNAME = "C", CID = 2 }, new State { SID = 4, SNAME = "D", CID = 2 }, new State { SID = 5, SNAME = "E", CID = 3 }, new State { SID = 6, SNAME = "F", CID = 3 });
        }
    }
}
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
   public interface IRepository<T> where T: class
    {
        Task<IEnumerable<T>> Gets();
        Task<T> Get(int ID);
        Task<T> Save(T t);
        Task<string> Update(T t);
        Task<string> Delete(int ID);
        Task<string> SaveAll(List<T> lst);
        Task<string> DeleteAll(List<T> lst);
    }
}
-
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.DAL
{
    public class Repository<T> : IRepository<T>  where T : class
    {
        #region
        private readonly AppDbContext Context;
        #endregion
        public Repository(AppDbContext context)
        {
            this.Context = context;
        }
        public async Task<string> Delete(int ID)
        {
            Context.Set<T>().Remove(await Context.Set<T>().FindAsync(ID));
            await Context.SaveChangesAsync();
            return "Data Deleted.";
        }

        public async Task<string> DeleteAll(List<T> lst)
        {
            Context.Set<T>().RemoveRange(lst);
            await Context.SaveChangesAsync();
            return "All Data Deleted.";
        }

        public async Task<T> Get(int ID)
        {
            return await Context.Set<T>().FindAsync(ID);
        }

        public async Task<IEnumerable<T>> Gets()
        {
            return await Context.Set<T>().ToListAsync();
        }

        public async Task<T> Save(T t)
        {
            Context.Set<T>().Add(t);
            await Context.SaveChangesAsync();
            return t;
        }

        public async Task<string> SaveAll(List<T> lst)
        {
            Context.Set<T>().AddRange(lst);
            await Context.SaveChangesAsync();
            return "All Data Saved.";
        }

        public async Task<string> Update(T t)
        {
            Context.Set<T>().Update(t);
            await Context.SaveChangesAsync();
            return "Data Updated.";
        }
    }
}
-
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication6.DAL;

namespace WebApplication6.Models
{
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<EMP, EMPVM>();
            CreateMap<EMPVM, EMP>();
            CreateMap<Newemp, NEWEMPVM>();
            CreateMap<NEWEMPVM, Newemp>();
        }
    }
}
-
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication6.Models
{
    public class NEWEMPVM
    {

        public NEWEMPVM()
        {
            HOBBY = new List<string>();
            Lhobby = new List<SelectListItem>();
            LCID = new List<SelectListItem>();
            LSID = new List<SelectListItem>();
        }
        public int EID { get; set; }
        [Required]
        public string NAME { get; set; }
        [Required]
        [DataType(DataType.MultilineText)]
        public string ADDRESS { get; set; }
        [Required]
        public string GENDER { get; set; }
        [Required]
        [EmailAddress]
        public string EMAIL { get; set; }
        [Required]
        public Decimal? SALARY { get; set; }
        [Required]
        public DateTime? DOJ { get; set; }
        [Required]
        public List<string> HOBBY { get; set; }
        public List<SelectListItem> Lhobby { get; set; }
        [Required]
        [Display(Name = "COUNTRY")]
        public int CID { get; set; }
        public List<SelectListItem> LCID { get; set; }
        [Required]
        [Display(Name = "STATE")]
        public int SID { get; set; }
        public List<SelectListItem> LSID { get; set; }
        [Required(ErrorMessage ="Please select a photo.")]
        public IFormFile PHOTO { get; set; }
        public string PATH { get; set; }

        [Required]

        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]

        [DataType(DataType.Password)]

        [Display(Name = "Password")]

        [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{6,100}$", ErrorMessage = "Password contains at least one number,one uppercase,one lowercase & one special charecter .")]

        public string Password { get; set; }

        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Invalid mobile number.")]

        public string Mobile { get; set; }

[RegularExpression(@"^(\d{6,9})$", ErrorMessage = "Zip code will only accept numeric digits with length 6 digit")]
        [RegularExpression(@"\d{5}", ErrorMessage = "Zip code will only accept numeric digits with length 5 digit")]

[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Please enter letters only")]

        public void fillddl(List<SelectListItem> cl, List<SelectListItem> hl, List<SelectListItem> sl = null)
        {
            LCID = cl;
            Lhobby = hl;
            LSID = sl;
        }
    }
}
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication6.DAL;
using WebApplication6.Models;

namespace WebApplication6
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(MappingProfile));
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;DataBase=Testdb0;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"));
            services.AddScoped<IRepository<Country>, Repository<Country>>();
            services.AddScoped<IRepository<State>, Repository<State>>();
            services.AddScoped<IRepository<Hobby>, Repository<Hobby>>();
            services.AddScoped<IRepository<Hobbymap>, Repository<Hobbymap>>();
            services.AddScoped<IRepository<EMP>, Repository<EMP>>();
            services.AddScoped<IRepository<Newemp>, Repository<Newemp>>();
            services.AddScoped<IRepository<Hobbym>, Repository<Hobbym>>();
            services.AddControllersWithViews()
          .AddJsonOptions(options =>
          {
              options.JsonSerializerOptions.PropertyNamingPolicy = null;
              //options.JsonSerializerOptions.Converters.Add(new WebApplication1.Models.LongToStringConverter());
          });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
-
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebApplication6.DAL;
using WebApplication6.Models;


namespace WebApplication6.Controllers
{
    public class NewEmpController : Controller
    {
        #region
        private readonly IRepository<Country> ic;
        private readonly IRepository<State> ist;
        private readonly IRepository<Hobby> ih;
        private readonly IRepository<Hobbym> ihm;
        private readonly IRepository<Newemp> ie;
        private readonly IMapper mapper;
        private readonly IHostingEnvironment hostingEnvironment;
        #endregion
        public NewEmpController(IRepository<Country> ic, IRepository<State> ist,
            IRepository<Hobby> ih, IRepository<Hobbym> ihm, IRepository<Newemp> ie, IMapper mapper, IHostingEnvironment hostingEnvironment)
        {
            this.ic = ic;
            this.ist = ist;
            this.ih = ih;
            this.ihm = ihm;
            this.ie = ie;
            this.mapper = mapper;
            this.hostingEnvironment = hostingEnvironment;
        }
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var lst = await ie.Gets();
            return View(lst.ToList());
        }
        [HttpGet]
        public async Task<IActionResult> Create()
        {
            NEWEMPVM nEWEMPVM = new NEWEMPVM();
            var data = await ic.Gets();
            nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), new List<SelectListItem>());
            return View(nEWEMPVM);
        }
        [HttpGet]
        public async Task<IActionResult> Fillddl(int CID)
        {
            var data = await ist.Gets();
            return Json(data.Where(m => m.CID == CID).ToList());
        }
        [HttpGet]
        public async Task<IActionResult> Edit(int id)
        {
            Newemp newemp = await ie.Get(id);
            NEWEMPVM nEWEMPVM = new NEWEMPVM();
            mapper.Map(newemp, nEWEMPVM);
            var data = await ic.Gets();
            nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), ist.Gets().Result.Where(m => m.CID == nEWEMPVM.CID).Select(p => new SelectListItem { Value = p.SID.ToString(), Text = p.SNAME }).ToList());
            var data1= await ihm.Gets();
            nEWEMPVM.HOBBY = data1.Where(m => m.EID == id).Select(p => p.HID.ToString()).ToList();
            return View("Create", nEWEMPVM);
        }
        [HttpPost]
        public async Task<IActionResult> Create(NEWEMPVM nEWEMPVM)
        {
            Newemp emp = new Newemp();
            mapper.Map(nEWEMPVM, emp);
            if (nEWEMPVM.EID > 0)
                ModelState.Remove("PHOTO");
            if (ModelState.IsValid)
            {

                if (nEWEMPVM.PHOTO != null)
                {
                    string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Image");
                    string uniqueFileName = Guid.NewGuid().ToString() + "_" + nEWEMPVM.PHOTO.FileName.Substring(3);
                    string filePath = Path.Combine(uploadsFolder, nEWEMPVM.PHOTO.FileName);
                    nEWEMPVM.PHOTO.CopyTo(new FileStream(filePath, FileMode.Create));
                    emp.PATH = nEWEMPVM.PHOTO.FileName;
                }
                if (nEWEMPVM.EID < 1)
                {
                    emp = await ie.Save(emp);
                }
                else
                {
                    string t = await ie.Update(emp);
                    t = await ihm.DeleteAll(ihm.Gets().Result.Where(m => m.EID == nEWEMPVM.EID).ToList());
                }
                string s = await ihm.SaveAll(nEWEMPVM.HOBBY.Select(x => new Hobbym { EID = emp.EID, HID = Convert.ToInt32(x) }).ToList());
                return RedirectToAction("Index");
            }
            else
            {
                var data = await ic.Gets();
                nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), ist.Gets().Result.Where(m => m.CID == nEWEMPVM.CID).Select(p => new SelectListItem { Value = p.SID.ToString(), Text = p.SNAME }).ToList());
                return View(nEWEMPVM);
            }

        }
        [HttpGet]
        public async Task<IActionResult> Delete(int id)
        {
            await ie.Delete(id);
         string   t = await ihm.DeleteAll(ihm.Gets().Result.Where(m => m.EID == id).ToList());
            return RedirectToAction("Index");
        }
    }
}
-
@model IEnumerable<WebApplication6.DAL.Newemp>

@{
    ViewData["Title"] = "Index";
}


<p>
    <a asp-action="Create" class="btn btn-primary">Add New</a>
</p>
<table class="table table-bordered table-hover" id="tb">
    <thead class="bg-primary">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ADDRESS)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GENDER)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EMAIL)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SALARY)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.DOJ)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PATH)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
               
                <td>
                    @Html.DisplayFor(modelItem => item.NAME)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ADDRESS)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.GENDER)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EMAIL)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.SALARY)
                </td>
                <td>
                    @{ 
                        string s = string.Format("{0:dd-MM-yyyy}", item.DOJ);
                    }
                   @s
                </td>
                <td>
                    <img height="50" width="50" src="@("Image/"+item.PATH)"/>
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new {  id=item.EID }) |
                    @Html.ActionLink("Delete", "Delete", new {  id=item.EID })
                </td>
            </tr>
        }
    </tbody>
</table>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        var table = $("#tb").DataTable({
            "order": [[0, "asc"]],
            "lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]],
            "scroller": true,
            "orderClasses": false,
        });
    });

</script>
-
@model WebApplication6.Models.NEWEMPVM

@{
    ViewData["Title"] = "Create";
}


<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>

            <div class="form-group">
                <label asp-for="NAME" class="control-label"></label>
                <input asp-for="NAME" class="form-control" />
                <input asp-for="EID" type="hidden" />
                <span asp-validation-for="NAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ADDRESS" class="control-label"></label>
                <textarea asp-for="ADDRESS" class="form-control"></textarea>
                <span asp-validation-for="ADDRESS" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="GENDER" class="control-label"></label>
                <input asp-for="GENDER" type="radio" value="Male" />Male
                <input asp-for="GENDER" type="radio" value="Female" />Female
                <span asp-validation-for="GENDER" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="EMAIL" class="control-label"></label>
                <input asp-for="EMAIL" class="form-control" />
                <span asp-validation-for="EMAIL" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SALARY" class="control-label"></label>
                <input asp-for="SALARY" class="form-control" />
                <span asp-validation-for="SALARY" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DOJ" class="control-label"></label>
                <input asp-for="DOJ" class="form-control" />
                <span asp-validation-for="DOJ" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="HOBBY" class="control-label"></label>
                <select asp-for="HOBBY" asp-items="Model.Lhobby" class="form-control" multiple></select>
                <span asp-validation-for="HOBBY" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CID" class="control-label"></label>
                <select asp-for="CID" asp-items="Model.LCID" class="form-control">
                    <option value="">Select</option>
                </select>
                <span asp-validation-for="CID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="SID" class="control-label"></label>
                <select asp-for="SID" asp-items="Model.LSID" class="form-control">
                    <option value="">Select</option>
                </select>
                <span asp-validation-for="SID" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="PHOTO" class="control-label"></label>
                <input asp-for="PHOTO" type="file" class="form-control" />
                <input type="hidden" asp-for="PATH" />
                <span asp-validation-for="PHOTO" class="text-danger"></span>
            </div>

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#DOJ').prop("type", "text");
        $('#HOBBY').chosen();
      
      
        $('#DOJ').datetimepicker({
            format:'DD-MM-YYYY'
        });
        var id =@Html.Raw(Json.Serialize(Model.EID));
        if (id == 0) {
            $('#DOJ').val('');
            //$("#PHOTO").rules("remove", "required");
            //$("#PHOTO").rules("add", "required");
        }  
        else {
             $("#PHOTO").removeAttr('data-val-required');
            var dt = new Date(@Html.Raw(Json.Serialize(Model.DOJ)));
              $('#DOJ').val((dt.getDate() < 10 ? ("0" + dt.getDate()) : dt.getDate()) + "-" + (parseInt(dt.getMonth() + 1) < 10 ? ("0" + parseInt(dt.getMonth() + 1)) : parseInt(dt.getMonth() + 1)) + "-" + dt.getFullYear());
        }
        $('#CID').change(function () {
            $('#SID').empty().append("<option>Select</option>");
            $.ajax({
                url: '@Url.Action("Fillddl","NewEmp")',
                data: { CID: $(this).val() },
                success: function (data) {
                    $.each(data, function (i, v) {
                         $('#SID').append("<option value="+v.SID+">"+v.SNAME+"</option>");
                    });
                }
            });
        });
    });
</script>