Friday, 29 November 2024

CRUD opreation in MVC





DEPTVM :

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

namespace WebApplication1.Models
{
    public class DEPTVM
    {
        public DEPTVM()
        {
            lCID = new List<SelectListItem>();
            lSID= new List<SelectListItem>();
            LHOBBY= new List<SelectListItem>();
            HOBBY=new List<string>();
        }
        public int EID { get; set; }
        [Required(ErrorMessage ="Name should not be blank.")]
        public string NAME { get; set; }
        [DataType(DataType.MultilineText)]
        [Required(ErrorMessage = "Address should not be blank.")]
        public string ADDRESS { get; set; }
        [DataType(DataType.Password)]
        [Required(ErrorMessage = "Password should not be blank.")]
        [StringLength(8,MinimumLength =6,ErrorMessage ="Password length between 6 to 8 charecters long.")]
        public string PASSWORD { get; set; }
       
        [DataType(DataType.Password)]
        [DisplayName("CONFIRM PASSWORD")]
        [Required(ErrorMessage = "Confirm password should not be blank.")]
        [System.Web.Mvc.Compare("PASSWORD",ErrorMessage ="Password and comfirm password must be same.")]
        public string CPASSWORD { get; set; }
        [Required(ErrorMessage = "Please select a gender.")]
        public string GENDER { get; set; }
        [Required(ErrorMessage = "Email should not be blank.")]
        [DataType(DataType.EmailAddress,ErrorMessage ="Invalid email id.")]
        public string EMAIL { get; set; }
        [Required(ErrorMessage = "Salary should not be blank.")]
        public decimal? SALSRY { get; set; }
        [Required(ErrorMessage = "Please select a DOB.")]
        public DateTime? DOB { get; set; }
        [DisplayName("COUNTRY")]
        [Required(ErrorMessage = "Please select a country.")]
        public int CID { get; set; }
        public List<SelectListItem> lCID { get; set; }
        [Required(ErrorMessage = "Please select a state.")]
        [DisplayName("STATE")]
        public int SID { get; set; }
        public List<SelectListItem> lSID { get; set; }
        [Required(ErrorMessage = "Please select a hobby.")]
        public List<string> HOBBY { get; set; }
        public List<SelectListItem> LHOBBY { get; set; }
        [DisplayName("PHOTO")]
        [Required(ErrorMessage = "Please select a photo.")]
        public HttpPostedFileBase FPATH { get; set; }
        public void fillddl(List<SelectListItem> cl,List<SelectListItem> sl, List<SelectListItem> hl)
        {
            lCID = cl;
            lSID = sl;
            LHOBBY= hl;
        }
    }
}

GEMP :

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel;

using System.Linq;

using System.Web;

using System.Web.Mvc;


namespace WebApplication1.Models

{

    public class GEMP

    {

        public int EID { get; set; }

        public string NAME { get; set; }

      

        public string ADDRESS { get; set; }

      

        public string PASSWORD { get; set; }

      

    

        public string GENDER { get; set; }

        public string EMAIL { get; set; }

        public decimal? SALSRY { get; set; }

        public DateTime? DOB { get; set; }

        public string COUNTRY { get; set; }

        public string STATE { get; set; }

        public string HOBBY { get; set; }

        public string PATHA { get; set; }

        public List<HOBBY> HOBBYs { get; set; }



    }

}

DeptController :


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using WebApplication1.Models;


namespace WebApplication1.Controllers

{

    public class DeptController : Controller

    {

        [HttpGet]

        public ActionResult Index()

        {

            using(Database1Entities1 obj=new Database1Entities1())

            {

                List<GEMP> lx = (from x in obj.EMPs

                                 join y in obj.COUNTRies on x.CID equals y.SID

                                 join z in obj.STATEs on x.SID equals z.SID

                                 select new GEMP()

                                 {

                                     EID = x.EID,

                                     NAME = x.NAME,

                                     PASSWORD = x.PASSWORD,

                                     ADDRESS = x.ADDRESS,

                                     GENDER = x.GENDER,

                                     SALSRY = x.SALARY.Value,

                                     EMAIL = x.MAIL,

                                     DOB = x.DOB.Value,

                                     PATHA = x.PATH,

                                     COUNTRY = y.SNAME,

                                     STATE = z.SNAME,

                                    HOBBYs = obj.HOBBies.Where(o => obj.HOBBYMAPs.Where(m => m.EID == x.EID).Select(n => n.HID).ToList().Contains(o.HID)).ToList()

                                 }).ToList();


            return View(lx);

            }

           

        }

        [HttpGet]

        public ActionResult Edit(int id)

        {

            using (Database1Entities1 obj = new Database1Entities1())

            {

                EMP dEPTVM = obj.EMPs.Find(id);

                DEPTVM eMP = new DEPTVM();

                eMP.EID = dEPTVM.EID;

                eMP.NAME = dEPTVM.NAME;

                eMP.ADDRESS = dEPTVM.ADDRESS;

                eMP.GENDER = dEPTVM.GENDER;

                eMP.EMAIL = dEPTVM.MAIL;

                eMP.SALSRY = dEPTVM.SALARY;

                eMP.DOB = dEPTVM.DOB;

                eMP.PASSWORD = dEPTVM.PASSWORD;

                eMP.fillddl(obj.COUNTRies.Select(m => new SelectListItem { Value = m.SID.ToString(), Text = m.SNAME }).ToList(),obj.STATEs.Where(q=>q.CID== dEPTVM.CID).Select(r=>new SelectListItem {Value=r.SID.ToString(),Text=r.SNAME }).ToList(), obj.HOBBies.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList());

                eMP.CID = dEPTVM.CID.Value;

                eMP.SID = dEPTVM.SID.Value;

                eMP.HOBBY = obj.HOBBYMAPs.Where(m => m.EID == dEPTVM.EID).Select(n => n.HID.ToString()).ToList();

                return View(eMP);

            }

        }

        [HttpPost]

        public ActionResult Edit(DEPTVM dEPTVM)

        {

            using (Database1Entities1 obj = new Database1Entities1())

            {

                EMP eMP = obj.EMPs.Find(dEPTVM.EID);

                eMP.NAME = dEPTVM.NAME;

                eMP.ADDRESS = dEPTVM.ADDRESS;

                eMP.GENDER = dEPTVM.GENDER;

                eMP.MAIL = dEPTVM.EMAIL;

                eMP.SALARY = dEPTVM.SALSRY;

                eMP.DOB = dEPTVM.DOB;

                eMP.CID = dEPTVM.CID;

                eMP.SID = dEPTVM.SID;

                string s = string.Empty;

                if (dEPTVM.FPATH.ContentLength > 0)

                {

                    s = "/Image/" + dEPTVM.FPATH.FileName;

                    dEPTVM.FPATH.SaveAs(Server.MapPath(s));

                    eMP.PATH = s;

                }

                obj.SaveChanges();

                obj.HOBBYMAPs.RemoveRange(obj.HOBBYMAPs.Where(m=>m.EID== dEPTVM.EID));

                obj.SaveChanges();

                obj.HOBBYMAPs.AddRange(dEPTVM.HOBBY.Select(x => new HOBBYMAP { EID = eMP.EID, HID = Convert.ToInt32(x) }));

                obj.SaveChanges();

                return RedirectToAction("Index");

            }

        }

        [HttpGet]

        public ActionResult Create() 

        {

            using (Database1Entities1 obj = new Database1Entities1())

            {

                DEPTVM dEPTVM = new DEPTVM();

                dEPTVM.fillddl(obj.COUNTRies.Select(m => new SelectListItem { Value = m.SID.ToString(), Text = m.SNAME }).ToList(), new List<SelectListItem>(), obj.HOBBies.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList());

                return View(dEPTVM);

            }

        }

        [HttpPost]

        public ActionResult Create(DEPTVM dEPTVM) {

            using (Database1Entities1 obj = new Database1Entities1())

            {

                EMP eMP= new EMP();

                eMP.NAME=dEPTVM.NAME;

                eMP.ADDRESS = dEPTVM.ADDRESS;

                eMP.GENDER = dEPTVM.GENDER;

                eMP.MAIL = dEPTVM.EMAIL;

                eMP.SALARY = dEPTVM.SALSRY;

                eMP.DOB = dEPTVM.DOB;

                eMP.PASSWORD = dEPTVM.PASSWORD;

                eMP.CID = dEPTVM.CID;

                eMP.SID = dEPTVM.SID;

                string s=string.Empty;

                if (dEPTVM.FPATH.ContentLength > 0)

                {

                  

                    s = "/Image/"+dEPTVM.FPATH.FileName;

                    if (!System.IO.File.Exists(Server.MapPath("~"+s)))

                    {

                        dEPTVM.FPATH.SaveAs(Server.MapPath(s));

                    }

                    

                }

                eMP.PATH = s;

                obj.EMPs.Add(eMP);

                obj.SaveChanges();

                obj.HOBBYMAPs.AddRange(dEPTVM.HOBBY.Select(x => new HOBBYMAP { EID = eMP.EID, HID = Convert.ToInt32(x) }));

                obj.SaveChanges();

                return RedirectToAction("Index");

            }

        }

        [HttpGet]

        public ActionResult Delete(int id)

        {

            using (Database1Entities1 obj = new Database1Entities1())

            {

                EMP eMP = obj.EMPs.Find(id);

                obj.EMPs.Remove(eMP);

                obj.SaveChanges();

                obj.HOBBYMAPs.RemoveRange(obj.HOBBYMAPs.Where(m => m.EID == id));

                obj.SaveChanges();

                return RedirectToAction("Index");

            }

        }

        [HttpGet]

        public JsonResult filldl(int cid)

        {

            using (Database1Entities1 obj = new Database1Entities1())

            {

                return Json(obj.STATEs.Where(m=>m.CID==cid).ToList(),JsonRequestBehavior.AllowGet);

            }


            }

    }

}

Index View :


@model IEnumerable<WebApplication1.Models.GEMP>


@{

    ViewBag.Title = "Index";

}


<h2>Index</h2>


<p>

    @Html.ActionLink("Create New", "Create")

</p>

<table class="table table-bordered table-hover table-responsive table-dark">

    <tr class="table-danger">

        <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.GENDER)

        </th>

       

        <th>

            @Html.DisplayNameFor(model => model.SALSRY)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.DOB)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.COUNTRY)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.STATE)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.HOBBY)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.PATHA)

        </th>

        <th>ACTIONS</th>

    </tr>


@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.GENDER)

        </td>

       

        <td>

            @Html.DisplayFor(modelItem => item.SALSRY)

        </td>

        <td>

            @{ 

                string t = string.Format("{0:dd-MMM-yy}", item.DOB);

            }

            @t

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.COUNTRY)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.STATE)

        </td>

        <td>

            @{

                string s = string.Empty;

                s = string.Join(",", item.HOBBYs.Select(p => p.HNAME));



            }

            @s

        </td>

        <td>

            <img height="50" width="50" src="@item.PATHA" alt="avtar" />

        </td>

        <td>

            @Html.ActionLink("Edit", "Edit", new {  id=item.EID }) |

            @Html.ActionLink("Delete", "Delete", new {  id=item.EID })

        </td>

    </tr>

}

</table>


Create View :

@model WebApplication1.Models.DEPTVM


@{

    ViewBag.Title = "Create";

}


<h2>Create</h2>



@using (Html.BeginForm("Create","Dept",FormMethod.Post,new { @enctype = "multipart/form-data" }))

{

    @Html.AntiForgeryToken()


<div class="form-horizontal">

    <h4>DEPTVM</h4>

    <hr />

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


    <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 { @class = "" })Male &nbsp;

            @Html.RadioButtonFor(model => model.GENDER, "Female", new { @class = "" })Female

            @Html.ValidationMessageFor(model => model.GENDER, "", 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.SALSRY, htmlAttributes: new { @class = "control-label col-md-2" })

        <div class="col-md-10">

            @Html.EditorFor(model => model.SALSRY, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.SALSRY, "", new { @class = "text-danger" })

        </div>

    </div>


    <div class="form-group">

        @Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })

        <div class="col-md-10">

            @Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.DOB, "", 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.lCID, "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.lSID, "Select", new { @class = "form-control" })

            @Html.ValidationMessageFor(model => model.SID, "", 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">

            @Html.ListBoxFor(model => model.HOBBY, Model.LHOBBY, new { @class = "form-control" } )

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

        </div>

    </div>

    <div class="form-group">

        @Html.LabelFor(model => model.FPATH, htmlAttributes: new { @class = "control-label col-md-2" })

        <div class="col-md-10">

            @Html.TextBoxFor(model => model.FPATH,  new { @class = "form-control",type="file" } )

            @Html.ValidationMessageFor(model => model.FPATH, "", 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>

}


<div>

    @Html.ActionLink("Back to List", "Index")

</div>


@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")

<script>

    $(function () {

         $('#CID').change(function () {


     $.ajax({

         url:  "@Url.Action("filldl", "Dept")",

         method: 'GET',

         datatype: 'json',

         data: {

             "cid": parseInt($(this).val())

         },

         success: function (data) {

             $('#SID').empty().append("<option value='0'>Select</option>")

             for (var i = 0; i < data.length; i++) {

                 $('#SID').append("<option value=" + data[i].SID + ">" + data[i].SNAME + "</option>")

             }

         },

         error: function (jqXHR) {

             alert(jqXHR.responseText);

         }

     });

 });


    });

</script>

}

Edit View :

@model WebApplication1.Models.DEPTVM

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>


@using (Html.BeginForm("Edit", "Dept", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
      
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.NAME, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.HiddenFor(m=>m.EID)
                @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 { @class = "" })Male &nbsp;
                @Html.RadioButtonFor(model => model.GENDER, "Female", new { @class = "" })Female
                @Html.ValidationMessageFor(model => model.GENDER, "", 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.SALSRY, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SALSRY, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SALSRY, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DOB, "", 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.lCID, "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.lSID, "Select", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.SID, "", 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">
                @Html.ListBoxFor(model => model.HOBBY, Model.LHOBBY, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.HOBBY, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.FPATH, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.FPATH, new { @class = "form-control", type = "file" })
                @Html.ValidationMessageFor(model => model.FPATH, "", 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>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script>
    $(function () {
         $('#CID').change(function () {

     $.ajax({
         url:  "@Url.Action("filldl", "Dept")",
         method: 'GET',
         datatype: 'json',
         data: {
             "cid": parseInt($(this).val())
         },
         success: function (data) {
             $('#SID').empty().append("<option value='0'>Select</option>")
             for (var i = 0; i < data.length; i++) {
                 $('#SID').append("<option value=" + data[i].SID + ">" + data[i].SNAME + "</option>")
             }
         },
         error: function (jqXHR) {
             alert(jqXHR.responseText);
         }
     });
 });

    });
    </script>
}