Editing a Model in ASP.NET MVC

How to Edit a Model in ASP.NET MVC

In this article, I am going to discuss how to edit a model in ASP.NET MVC Application. Please read our previous article before proceeding to this article as we are going to work with the same example. In our previous article, we discussed how to update the model using UpdateModel and TryUpdateModel function.

Here, in this article, I will show you how to update a model in ASP.NET MVC application step by step.

Step1: Creating the Edit action method.

Please copy and paste the following “Edit” action method within the “EmployeeController” and include the System.Linq namespace. Here, first, we are retrieving all the employees and then finding the employees by using the Linq FirstOrDefault method. But in real-time you need to create one method in your business layer and that method should return the employee based on the id.

[HttpGet]
public ActionResult Edit(int id)
{
    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
    Employee employee = employeeBusinessLayer.GetAllEmployess().FirstOrDefault(emp => emp.ID == id);
    return View(employee);
}

Points to note:

  1. This method is decorated with the [HttpGet] attribute. So this method only responds to HTTP get requests when editing the data.
  2. The”Edit” action method also receives the “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
Step2: Creating the “Edit” view

Now let’s add the “Edit” view. To do this right-click on the “Edit” action method and then select “Add View” from the context menu. Set

View name = “Edit”
Template = “Edit”
Model class = Employee (BusinessLayer)

Click on the “Add” button as shown below. This should add “Edit.cshtml” view to the “Employee” folder which is within the “Views” folder.

Creating Edit View in ASP.NET MVC Application

Run the application and navigate to http://localhost:54094/Employee/Index. This page should display the list of all the employees. Click on the “Edit” link which is available on the right side of the employee. The “Edit” page should display the details of the “Employee” that is being edited as shown below.

How to edit a model in asp.net mvc application

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”.

How to Edit a Model in ASP.NET MVC

With the above changes in place, the complete code in Edit.cshtml view as below.

@model BusinessLayer.Employee

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

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

        <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.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Gender", new List<SelectListItem>
{
   new SelectListItem { Text = "Male", Value="Male" },
   new SelectListItem { Text = "Female", Value="Female" }
}, "Select Gender", new { @class = "form-control" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
            </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>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

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 the “EmployeeBusinessLayer” class in the “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();
    }
}
Creating the Edit Post Method:

Please copy and paste the following “Edit” (HttpPost) action method in “EmployeeController“. 

[HttpPost]
public ActionResult Edit(Employee employee)
{
    if (ModelState.IsValid)
    {
        EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
        employeeBusinessLayer.UpdateEmmployee(employee);
        return RedirectToAction("Index");
    }
    return View(employee);
}
Code Explanation:
  1. The above Edit action method is decorated with the [HttpPost] attribute. So this method only responds to HTTP post requests when updating data.
  2. This method receives the modified “Employee” object as a parameter. 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 the “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 am going to discuss how unintended updates can happen in MVC and how to prevent unintended updates in MVC. Here, in this article, I try to explain how to update the Model in ASP.NET MVC application step by step with a simple example. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article

6 thoughts on “Editing a Model in ASP.NET MVC”

  1. If it is only me or I do not know, I can’t find the edit [HttpPost] and the stored procedure, I managed to do it myself referencing the post method. BTW, thanks for your tutorial.

    For those who want my referenced code,
    the save method for EmployeeBusinessLayer,

    public void SaveEmployee(Employee employee)
    {
    //Creating the connection string
    string connectionString = ConfigurationManager.ConnectionStrings[“DBCS”].ConnectionString;
    //Establishing the connection to the database
    using (SqlConnection con = new SqlConnection(connectionString))
    {
    //Creating the command object by passing the stored procedure and connection object as argument
    //This stored procedure is used to store the employee in to the database
    SqlCommand cmd = new SqlCommand(“spSaveEmployee”, con);
    //Specifying the command as stored procedure
    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);
    //Same for all other parameters (Gender, City, DateOfBirth )
    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);
    //Open the connection and execute the command on ExecuteNonQuery method
    con.Open();
    cmd.ExecuteNonQuery();
    }
    }
    ————————————– end ————————————————————–

    Stored Procedure sql command,

    Create procedure spSaveEmployee
    @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

    ————————————– end ————————————————————–

    For those who want the edit post method in your controller, you can find it in the next article. 😀 hope you can get it

Leave a Reply

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