Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Monday, 7 November 2016

Insert Update Delete Data First approach using Entity Framework

Let's see with an example:

Tables Used
select * from employeeMaster
select * from employeeLocationDetails
select * from employeeDesignationDetails



Step 1 : Create new MVC Project


Step 2 : Change the Name, Location of Project


Step 3 : Choose Empty MVC Application


Step 4 : Right click on Model and Add new item




Step 5 : Create Model from database


Step 6 : Create new connection 

Step 7 : add the server name

 Step 8 :Add connection string name


 Step 9 : Select the tables you need in your model. select the model namespace


Step 10 : Save the Changes


Step 11 : Right click on controller and add new controller




Step 12 : Run the Application

 Step 13 : Create New Employee


 Step 14 : Update Employee



 Step 15 : Check Employee Details

 Step 16 : Delete the Employee




Include and Exclude Properties for Update in MVC

Include and Exclude Properties
They help in preventing updates in MVC. A read only field can be easily updated using tools like fiddler. To prevent such unintended updates we can use Include and Exclude Properties.

This is What we want to Achieve

 To Reach to the Index screen of above Screen Shot. Follow below link
2. Adding Create New option
3. Updating and Deleting Record in MVC

Step 1 : Make the following change in Edit Post back request in Employee Controller

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int id)
        {
            EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
            Employee employee = employeeBuisnessLayer.Employees.Single(emp => emp.EmpID == id);
            UpdateModel(employee, null, null, new string[] { "EmpName"});//Exclude List

            if (ModelState.IsValid)
            {
                employeeBuisnessLayer.Employee_Update(employee);
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }

        }


OR

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int id)
        {
            EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
            Employee employee = employeeBuisnessLayer.Employees.Single(emp => emp.EmpID == id);
            UpdateModel(employee, new string[] { "EmpDesignation" });//Include List

            if (ModelState.IsValid)
            {
                employeeBuisnessLayer.Employee_Update(employee);
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

OR

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post([Bind(Include = "EmpID,EmpDesignation")] Employee employee)
        {
            EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
            employee.EmpName = employeeBuisnessLayer.Employees.Single(emp => emp.EmpID == employee.EmpID).EmpName;
            if (ModelState.IsValid)
            {
                employeeBuisnessLayer.Employee_Update(employee);
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

OR

        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post([Bind(Exclude = "EmpName")] Employee employee)
        {
            EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
            employee.EmpName = employeeBuisnessLayer.Employees.Single(emp => emp.EmpID == employee.EmpID).EmpName;
            if (ModelState.IsValid)
            {
                employeeBuisnessLayer.Employee_Update(employee);
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

OR

In Employee Class
    public interface IEmployee
    {
        int EmpID { get; set; }
        string EmpDesignation { get; set; }
    }
    public class Employee : IEmployee
    {
        public int EmpID { get; set; }
        [Required]
        public string EmpName { get; set; }
        [Required]
        public string EmpDesignation { get; set; }

    }

In Employee Controller
        [HttpPost]
        [ActionName("Edit")]
        public ActionResult Edit_Post(int id)
        {
            EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
            Employee employee = employeeBuisnessLayer.Employees.Single(emp => emp.EmpID == id);
            UpdateModel<IEmployee>(employee);
            if (ModelState.IsValid)
            {
                employeeBuisnessLayer.Employee_Update(employee);
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

Step 2 : Run the Application





Updating and Deleting Record in MVC using Separate Buisness Layer

This is What we want to Achieve
To Reach to the Index screen of above Screen Shot. Follow below link


Procedure Used

CREATE proc EmployeeTest_Update
@EmpID int ,
@EmpName varchar(100),
@EmpDesignation varchar(100)
as
begin
Update EmployeeTest set
EmpName=@EmpName,
EmpDesignation=@EmpDesignation
where
EmpID=@EmpID
end

 AND

create proc EmplyeeTest_Delete
@EmpID int
As
Delete from EmployeeTest where EmpID=@EmpID

Step 22 : In the Employee Controller for getting the Edit form add Edit View.

        [HttpGet]
        public ActionResult Edit(int id)
        {
            EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
            Employee employee = employeeBuisnessLayer.Employees.Single(emp => emp.EmpID == id);
            return View(employee);
        }

Step 23 : Right click and select Add View


Step 24 : In Edit.cshtml preesnt inside Employee inside Views

@model BuisnessLayer.Employee

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
       
        <div class="form-horizontal">
            <h4>Employee</h4>
            <hr />
            @Html.ValidationSummary(true)
            <div class="form-group">
                @Html.HiddenFor(model => model.EmpID)
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.EmpName, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.EmpName)
                    @Html.ValidationMessageFor(model => model.EmpName)
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.EmpDesignation, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.EmpDesignation)
                    @Html.ValidationMessageFor(model => model.EmpDesignation)
                </div>
            </div>
   
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
   
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

Step 25 :  In EmployeeBuisnessLayer Add the following function

        public void Employee_Update(Employee employee)
        {
            String CS = ConfigurationManager.ConnectionStrings["EmplyoeeDB"].ConnectionString;
            using (SqlConnection sqlcon = new SqlConnection(CS))
            {
                SqlCommand sqlcmd = new SqlCommand("EmployeeTest_Update", sqlcon);
                sqlcmd.CommandType = System.Data.CommandType.StoredProcedure;
                sqlcmd.Parameters.AddWithValue("@EmpID", employee.EmpID);
                sqlcmd.Parameters.AddWithValue("@EmpName", employee.EmpName);
                sqlcmd.Parameters.AddWithValue("@EmpDesignation", employee.EmpDesignation);
                sqlcon.Open();
                sqlcmd.ExecuteNonQuery();
            }
        }

        public void Employee_Delete(int EmpID)
        {
            String CS = ConfigurationManager.ConnectionStrings["EmplyoeeDB"].ConnectionString;
            using (SqlConnection sqlcon = new SqlConnection(CS))
            {
                SqlCommand sqlcmd = new SqlCommand("EmplyeeTest_Delete", sqlcon);
                sqlcmd.CommandType = System.Data.CommandType.StoredProcedure;
                sqlcmd.Parameters.AddWithValue("@EmpID", EmpID);
                sqlcon.Open();
                sqlcmd.ExecuteNonQuery();
            }
        }

Step 26 : for posting the data add the following code in EmployeeController

        [HttpPost]
        public ActionResult Edit(Employee employee)
        {
            if (ModelState.IsValid)
            {
                EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
                employeeBuisnessLayer.Employee_Update(employee);
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }
Always use Delete with HTTPPost option to prevent security flaws
        [HttpPost]
        public ActionResult Delete(int id)
        {
            EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
            employeeBuisnessLayer.Employee_Delete(id);
            return RedirectToAction("Index");

        }

Step 27 : In Index.cshtml make the following change, Using Html.Beginform has been added

@foreach (var item in Model)
    {
        using (Html.BeginForm("Delete", "Employee", new { id = item.EmpID }))
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.EmpID)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EmpName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EmpDesignation)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.EmpID }) |
                    @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                    <input type="submit" value="Delete" onclick="return confirm('Are you sure you wat to delete employee: @item.EmpName')" />
                </td>
            </tr>
        }
    }

Step 28 : Adding Details functionality.
In the Employee Controller for getting the Details form add Details View.

        [HttpGet]
        public ActionResult Details(int id)
        {
            EmployeeBuisnessLayer employeeBuisnessLayer = new EmployeeBuisnessLayer();
            Employee employee = employeeBuisnessLayer.Employees.Single(emp => emp.EmpID == id);
            return View(employee);
        }

Step 29 : Right click and select Add View


Step 30 : In Details.cshtml presnt inside Employee inside Views

@model BuisnessLayer.Employee

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Employee</h4>
       <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.EmpID)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpID)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmpName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmpDesignation)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpDesignation)
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new {  id = Model.EmpID }) |
    @Html.ActionLink("Back to List", "Index")
</p>

Step 30 : In Index.cshtml make the following change

      @Html.ActionLink("Details", "Details", new { id = item.EmpID })


Step 32 : Run the Application


Click on Edit Button
Make your changes and Save
Click on Delete Button
Click on Details to get the Details of the Employee