Editing a Model in ASP.NET MVC

Editing Model in ASP.NET MVC

In this article, we will discuss editing model in MVC. Please read our last article of ASP.NET MVC Tutorials before proceeding to this article. We are going to work on the same example that we worked on the last article.

Step 1: Copy and paste the following “Edit” controller action method in “EmployeeController.cs” file.
[HttpGet]
public ActionResult Edit(int id)
{
    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
    Employee employee = employeeBusinessLayer.GetAllEmployess().Single(emp => emp.ID == id);
    return View(employee);
}
Please note:
  1. This method is decorated with [HttpGet] attribute. So this method only responds to HTTP get request when editing data.
  2. The”Edit” action method also receives “id” of the employee that is being edited. This “id” is used to retrieve the employee details.
  3. The employee object is passed to the view
Step 2: Add “Edit” view

          a) Right-click on the “Edit” controller action method and select “Add view” from the context menu

          b)Set
             View name = Edit

            Template = Edit

            Model class = “Employee”

            Finally click “Add” button

          c)This should add “Edit.cshtml” view to “Employee” folder in “Views” folder

Run the application and navigate to http://localhost:54094/Employee/Index. This page should list all the employees. Click on “Edit” link. The “Edit” page should display the details of the “Employee” being edited.

Notice that by default “textboxes” are used for editing. It is ideal to have a drop-down list for gender rather than a textbox. To achieve this make the following changes to “Edit.cshtml”

REPLACE THE FOLLOWING CODE
REPLACE THE FOLLOWING CODE
@Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })
WITH
@Html.DropDownList("Gender", new List<SelectListItem>
{
   new SelectListItem { Text = "Male", Value="Male" },
   new SelectListItem { Text = "Female", Value="Female" }
}, "Select Gender", new { @class = "form-control" })

Run the application. Edit an employee, and notice that a DropDownList is used for gender as expected.

Create a stored procedure to update employee data.
Create procedure spUpdateEmployee      
  @Id int,
  @Name nvarchar(50),      
  @Gender nvarchar (10),      
  @City nvarchar (50), 
  @Salary decimal(18,2),     
  @DateOfBirth DateTime 
as      
Begin      
  Update	Employee Set
    Name = @Name,
    Gender = @Gender,
    City = @City,
    Salary = @Salary,
    DateOfBirth = @DateOfBirth
  Where   Id = @Id
End
Add the following “SaveEmployee()” method to “EmployeeBusinessLayer” class in “BusinessLayer” project.

This method is used to update employee data to the database table.

public void UpdateEmmployee(Employee employee)
{
    string connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("spUpdateEmployee", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter paramId = new SqlParameter();
        paramId.ParameterName = "@Id";
        paramId.Value = employee.ID;
        cmd.Parameters.Add(paramId);

        SqlParameter paramName = new SqlParameter();
        paramName.ParameterName = "@Name";
        paramName.Value = employee.Name;
        cmd.Parameters.Add(paramName);

        SqlParameter paramGender = new SqlParameter();
        paramGender.ParameterName = "@Gender";
        paramGender.Value = employee.Gender;
        cmd.Parameters.Add(paramGender);

        SqlParameter paramCity = new SqlParameter();
        paramCity.ParameterName = "@City";
        paramCity.Value = employee.City;
        cmd.Parameters.Add(paramCity);

        SqlParameter paramSalary = new SqlParameter();
        paramSalary.ParameterName = "@Salary";
        paramSalary.Value = employee.Salary;
        cmd.Parameters.Add(paramSalary);

        SqlParameter paramDateOfBirth = new SqlParameter();
        paramDateOfBirth.ParameterName = "@DateOfBirth";
        paramDateOfBirth.Value = employee.DateOfBirth;
        cmd.Parameters.Add(paramDateOfBirth);

        con.Open();
        cmd.ExecuteNonQuery();
    }
}
Copy and paste the following “Edit” controller action method in “EmployeeController.cs” file. 
[HttpPost]
public ActionResult Edit(Employee employee)
{
    if (ModelState.IsValid)
    {
        EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
        employeeBusinessLayer.UpdateEmmployee(employee);
        return RedirectToAction("Index");
    }
    return View(employee);
}
Please note:
  1. This method is decorated with [HttpPost] attribute. So this method only responds to HTTP post request when updating data.
  2. The”Edit” action method receives the modified “Employee” object. This object is then passed to UpdateEmmployee() method which updates the employee details. After the employee details are saved the user is redirected to “Index” action.
  3. If there are model validation errors none of the code in the IF block gets executed. In this case, the user stays on the “Edit” view. Since we are passing “Employee” object to the “Edit” view the user gets to see the validation errors. This allows him to fix those errors and re-submit the view.

In the next article, I will discuss how unintended updates can happen in MVC and how to prevent unintended updates in MVC.

SUMMARY

In this article, I try to explain how to update Model in ASP.NET MVC application step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article

Leave a Reply

Your email address will not be published. Required fields are marked *