Table of contents
1.
Introduction
2.
Steps to create Edit View
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

ASP.NET Create Edit View

Author Toohina Barua
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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.

Source

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.

Source

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.

Source

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.

Source

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:

Source

FAQs

  1. What is the purpose of the .csproj file?
    One of the most crucial files in our application is the project file. It instructs.NET on how to construct the project. In the.csproj file, all.NET projects declare their dependencies. Consider it a package.json file if you've worked with JavaScript before. The distinction is that this is an XML file rather than a JSON file.
     
  2. What is the purpose of the Program class?
    This class sets up the web server that will handle the requests. The host is in charge of the application's initialization and lifespan management and graceful shutdown.
     
  3. What is model binding in ASP.NET?
    The data for the model binding system comes from various places, including form fields, route data, and query strings. It also gives data to controllers and views in the form of method parameters and properties, converting plain string data to.NET objects and types in the process.
     
  4. What is an Action Method?
    An action method is a controller class method that has the following restrictions:
    It has to be open to the public. Methods that are private or protected are not permitted.
    It can't possibly be overloaded.
    It can’t be a static method.
    In response to an HTTP request, an action method performs an action.
     
  5. What is the Entity Framework?
    Entity Framework (EF) is a library that allows you to access a database in an object-oriented manner. It communicates with the database and translates database results to.NET classes and objects as an object-relational mapper.

Key Takeaways

We learned how to create an edit view in ASP.NET with a practical example from this article. Apart from this, you can also expand your knowledge by referring to these articles on Features Of ASP Net and ASP Full Form.


But this is not enough; you need something extra to excel in web development truly. If you want to learn more about web development, you can read our articles or take our highly curated Web Development course.

Live masterclass