Crud Application in Asp.NET MVC (Project Model) Part 1

 Controller Code:



        crud_application_modelEntities db = new crud_application_modelEntities();

        // GET: Employee

        public ActionResult Index()

        {

            return View();

        }

        [HttpGet]

        public ActionResult Create()

        {

            List<tbl_depart> dep = db.tbl_depart.ToList();

            ViewBag.dep_list = new SelectList(dep, "dep_id", "dep_name");

            return View();

        }


        [HttpPost]

        public ActionResult Create(employee_view_model evm)

        {

            List<tbl_depart> dep = db.tbl_depart.ToList();

            ViewBag.dep_list = new SelectList(dep, "dep_id", "dep_name");


            tbl_employee emp = new tbl_employee();


            emp.emp_name = evm.emp_name;

            emp.emp_email = evm.emp_email;

            emp.emp_contact = evm.emp_contact;

            emp.dep_id_fk = evm.dep_id;


            db.tbl_employee.Add(emp);


            db.SaveChanges();



            return RedirectToAction("Index");



            return View();

        }


View Code:


@model Crud_application_model.Models.employee_view_model




@{

    ViewBag.Title = "Create";

    Layout = "~/Views/Shared/_Layout.cshtml";

}


<h2>Create</h2>

@using (Html.BeginForm("Create", "Employee", FormMethod.Post))

{

    @Html.DropDownListFor(x => x.dep_id, ViewBag.dep_list as SelectList, "Select", new { @class = "form-control" })


    @Html.TextBoxFor(x => x.emp_name, new { @class = "form-control" })

    @Html.TextBoxFor(x => x.emp_email, new { @class = "form-control" })

    @Html.TextBoxFor(x => x.emp_contact, new { @class = "form-control" })


    <input type="submit" value="ADD" class=" = btn btn-primary" />



}


Database Code:


create database crud_application_model


use crud_application_model


create table tbl_depart

(

dep_id int primary key identity,

dep_name nvarchar(50) not null)


create table tbl_employee

(

emp_id int primary key identity,

emp_name nvarchar(50) not null,

emp_email nvarchar(50) not null,

emp_contact nvarchar(50) not null,

dep_id_fk int foreign key references tbl_depart(dep_id)


)


insert into tbl_depart values('IT'),('HR'),('Admin')


select * from tbl_employee


Comments