Loading

ASP.NET MVC

How to Editing a Model in ASP.NET MVC. The Complete ASP.NET MVC Developer Course 2022 [Videos].

In this Video, I am going to discuss how to edit a model in ASP.NET MVC Application. Please watch our previous Video before proceeding to this Video as we are going to work with the same example. In our previous Video, we discussed how to update the model using UpdateModel and TryUpdateModel function. Here, in this Video, 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 lets add the Edit view. To do this right-click on the Edit action method and then select Add View option from the context menu and then Set

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

Click on the “Add” button as shown below. This should add the “Edit.cshtml” view within 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 “UpdateEmployee()” 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.

See All

Comments (283 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET MVC / Youtube

What is MVC?

MVC is an architectural software design pattern that is used for developing interactive applications where their user interaction is involved and based on the user interaction some event handling has occurred. It is not only used for web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved.
28-jan-2022 /28 /283

ASP.NET MVC / Youtube

How to Creat First ASP.NET MVC Application using Visual Studio?

In this article, I am going to discuss how to create the first ASP.NET MVC Application step by step from scratch using Visual Studio 2015. You can use any version as per your choice but the step will remain the same. Please read our previous article before proceeding to this article where we gave a brief introduction to ASP.NET MVC Framework.
28-jan-2022 /28 /283

ASP.NET MVC / Youtube

What is ASP.NET MVC File and Folder Structure?

In this article, I am going to discuss the auto-generated ASP.NET MVC File and File Structure when we create a new ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create ASP.NET MVC 5 application step by step from scratch.
28-jan-2022 /28 /283