Introduction
Imagine a user saves their address on an online shopping website. The user orders things to be delivered to the address saved in the database. But what if the user changes their location! They need to edit their address! For that, they need an edit view on the website. We can create Edit View using ASP.NET, where we will provide the user the facility to edit and update data.
Steps to create Edit View
In the following sections, we'll develop an edit view where users can change the data.
The Student model class is shown below:
namespace MVCTutorials.Controllers
{
public class Student
{
public int StudentId { get; set; }
[Display( Name="Name")]
public string StudentName { get; set; }
public int Age { get; set; }
}
}
The processes involved in changing a student's record are outlined below:
1. Create the student list view, as seen below, including Edit action links for each Student.
Edit links in the list view send a HttpGet request to the StudentController's Edit() action method, matching StudentId in the query string. For instance, an edit link with a student John will append a StudentId to the request url because John's StudentId is 1 will be http://localhost:4736/edit/1.
2. Create an Edit (int id) HttpGET action method in the StudentController, as shown below.
HttpGet Edit() Action method (C#):
using MVCTutorials.Models;
namespace MVCTutorials.Controllers
{
public class StudentController : Controller
{
static IList<Student> studentList = new List<Student>{
new Student() { StudentId = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentId = 2, StudentName = "Steve", Age = 21 } ,
new Student() { StudentId = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentId = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentId = 5, StudentName = "Ron" , Age = 31 } ,
new Student() { StudentId = 4, StudentName = "Chris" , Age = 17 } ,
new Student() { StudentId = 4, StudentName = "Rob" , Age = 19 }
};
// GET: Student
public ActionResult Index()
{
//fetch students from the DB
return View(studentList.OrderBy(s => s.StudentId).ToList());
}
public ActionResult Edit(int Id)
{
//Get the student from the database in the application
//getting a student from collection for demo
var std = studentList.Where(s => s.StudentId == Id).FirstOrDefault();
return View(std);
}
}
}
Two tasks must be completed by the HttpGet Edit() action method:
- It should retrieve student data from the underlying data source with a StudentId that matches the argument Id.
- It should display the data in the Edit view so that the user can edit it.
A LINQ query is used in the above Edit() action method to retrieve a Student from the studentList collection whose StudentId matches the parameter Id. Then, pass the std object into View(std) to populate the edit view with that data. You can receive data from the database instead of the sample collection in a real-world application.
3. Right-click in the Edit() action method and select Add View... to create an Edit view. The Add View dialogue box will appear, as seen below.
Keep the view name Edit in the Add View dialogue box.
As illustrated below, select Edit Template and Student Model class from the dropdown menu.
To create the Edit.cshtml view in the /View/Student folder, click the Add button, as shown below.
/View/Student/Edit.cshtml
@model MVCTutorials.Models.Student
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.StudentId)
<div class="form-group">
@Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", 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>
The HtmlHelper method Html.BeginForm() is used to build the HTML form tag in Edit.cshtml. By default, Html.BeginForm sends a HttpPost request. When you click an edit link in the student list view, a Student data will appear, as shown below.
You can now make changes to the data and save it. Because we need to submit the form data as a part of the request body as a Student object, the Save button should send the HttpPOST request.
4. Now, as shown below, write the HttpPost action method Edit() to store the edited student object. As a result, there will be two Edit() action methods: HttpGet and HttpPost.
using MVCTutorials.Models;
namespace MVCTutorials.Controllers
{
public class StudentController : Controller
{
IList<Student> studentList = new List<Student>() {
new Student(){ StudentId=1, StudentName="John", Age = 18 },
new Student(){ StudentId=2, StudentName="Steve", Age = 21 },
new Student(){ StudentId=3, StudentName="Bill", Age = 25 },
new Student(){ StudentId=4, StudentName="Ram", Age = 20 },
new Student(){ StudentId=5, StudentName="Ron", Age = 31 },
new Student(){ StudentId=6, StudentName="Chris", Age = 17 },
new Student(){ StudentId=7, StudentName="Rob", Age = 19 }
};
// GET: Student
public ActionResult Index()
{
return View(studentList.OrderBy(s => s.StudentId).ToList());
}
public ActionResult Edit(int Id)
{
//get the student from the database in the real application
//getting a student from collection for demo
var std = studentList.Where(s => s.StudentId == Id).FirstOrDefault();
return View(std);
}
[HttpPost]
public ActionResult Edit(Student std)
{
//update student in DB in real-life application
//update list by removing old student and adding updated student for demo
var student = studentList.Where(s => s.StudentId == std.StudentId).FirstOrDefault();
studentList.Remove(student);
studentList.Add(std);
return RedirectToAction("Index");
}
}
}
The HttpPost Edit() action method in the previous example requires an object of the Student as an argument. Because it employs HTML helper methods @Html, the Edit() view will connect the form's data collection to the student model parameter. To display input textboxes, use EditorFor() for each property.
Redirect back to the Index() action method after updating the data in the database to see the revised student list.
Output: