Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 18 - Updating data in mvc

Suggested Videos 
Part 15 - Updatemodel function in MVC
Part 16 - Difference between UpdateModel and TryUpdateModel
Part 17 - Editing a model in mvc



In this video we will discuss updating data in mvc. Please watch Part 17, before proceeding.


Step 1: Create a stored procedure to update employee data.
Create procedure spSaveEmployee      
@Id int,
@Name nvarchar(50),      
@Gender nvarchar (10),      
@City nvarchar (50),      
@DateOfBirth DateTime 
as      
Begin      
 Update tblEmployee Set
Name = @Name,
Gender = @Gender,
City = @City,
DateOfBirth = @DateOfBirth
 Where Id = @Id
End



Step 2: Add the following "SaveEmployee()" method to "EmployeeBusinessLayer" class in "BusinessLayer" project. This method is used to save employee data to the database table.
public void SaveEmmployee(Employee employee)
{
    string connectionString =
            ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("spSaveEmployee", 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 paramDateOfBirth = new SqlParameter();
        paramDateOfBirth.ParameterName = "@DateOfBirth";
        paramDateOfBirth.Value = employee.DateOfBirth;
        cmd.Parameters.Add(paramDateOfBirth);

        con.Open();
        cmd.ExecuteNonQuery();
    }
}

Step 3: 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.SaveEmmployee(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 SaveEmployee() method, which saves 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.

6 comments:

  1. Here i want to clarify that in last edit function we need not to pass employee object

    return RedirectToAction("Index");
    }
    return View(employee);<= not necessary to pass employee
    }

    ReplyDelete
    Replies
    1. [HttpPost]
      public ActionResult Edit(Employee employee)
      {
      if (ModelState.IsValid)
      {
      EmployeeBusinessLayer employeeBusinessLayer =
      new EmployeeBusinessLayer();
      employeeBusinessLayer.SaveEmmployee(employee);

      return RedirectToAction("Index");
      }
      return View(employee);
      }
      Note that in he post method we are validating the input. if its valid we are posting the data else we are returning the user to the current view which takes employee as the parameter

      Delete
    2. It's important to return employee object. for example if you have a field with displayFor in Edit View. If you do Postback, the field will be empty because you did not return employee to the View.

      Delete
  2. who maintain the asp.net worker procsser

    ReplyDelete
  3. Typo in SaveEmmployee - code still works if you have use employeeBusinessLayer.SaveEmmployee.

    ReplyDelete
  4. why we use library class in mvc project
    and my second question why we add reference

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.