banner



How To Create Form In Mvc

Create Edit View in ASP.NET MVC

We created the list view in the Integrate Model, View, Controller chapter. Here, you will learn how to create the edit view where the users can edit the data. The following illustrates the steps involved in editing a student's record.

Editing Steps in ASP.NET MVC Application

The edit view will be rendered on the click of the Edit link in the student list view, which we already created the student list view in the Create a View chapter. Here, we will build the following edit view in order to edit a student record.

Edit View

The following figure describes how the edit functionality would work in ASP.NET MVC application.

Editing Steps in ASP.NET MVC App

The above figure illustrates the following steps.

1. The user clicks on the Edit link in the student list view, which will send the HttpGET request http://localhost/student/edit/{Id} with corresponding Id parameter in the query string. This request will be handled by the HttpGET action method Edit(). (by default action method handles the HttpGET request if no attribute specified)

2. The HttpGet action method Edit() will fetch student data from the database, based on the supplied Id parameter and render the Edit view with that particular Student data.

3. The user can edit the data and click on the Save button in the Edit view. The Save button will send a HttpPOST request http://localhost/Student/Edit with the Form data collection.

4. The HttpPOST Edit action method in StudentController will finally update the data into the database and render an Index page with the refreshed data using the RedirectToAction method as a fourth step.

So this will be the complete process to edit the data using the Edit view in ASP.NET MVC.

So let's start to implement the above steps.

The following is the Student model class.

                          namespace              MVCTutorials.Controllers {              public              class              Student              {              public              int              StudentId {              get;              set; }          [Display( Name="Name")]              public              string              StudentName {              get;              set; }              public              int              Age {              get;              set; }     } }                      

Step: 1

We have already created the student list view in the Create a View chapter, which includes the Edit action links for each Student, as shown below.

create view in asp.net mvc
List View

In the above list view, edit links send HttpGet request to the Edit() action method of the StudentController with corresponding StudentId in the query string. For example, an edit link with a student John will append a StudentId to the request url because John's StudentId is 1 e.g. http://localhost:<port number>/edit/1.

Step 2:

Now, create a HttpGET action method Edit(int id) in the StudentController, as shown below.

                          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 using Entity Framework here              return              View(studentList.OrderBy(s => s.StudentId).ToList());         }              public              ActionResult              Edit(int              Id)         {              //here, get the student from the database in the real application              //getting a student from collection for demo purpose              var              std = studentList.Where(s => s.StudentId == Id).FirstOrDefault();              return              View(std);         }     } }                      

The HttpGet Edit() action method must perform two tasks. First, it should fetch a student data from the underlying data source, whose StudentId matches the parameter Id. Second, it should render the Edit view with the data, so that the user can edit it.

In the above Edit() action method, a LINQ query is used to get a Student from the studentList collection whose StudentId matches with the parameter Id, and then pass that std object into View(std) to populate the edit view with this data. In a real-life application, you can get the data from the database instead of the sample collection.

At this point, if you run the application and click on the Edit link in the student list view, then you will get the following error.

edit view error
Edit View Error

The above error occurrs because we have not created an Edit view yet. By default, MVC framework will look for Edit.cshtml, Edit.vbhtml, Edit.aspx, or Edit.ascx file in /View/Student or /View/Shared folder.

Step 3:

To create Edit view, right-click in the Edit() action method and click on Add View... It will open Add View dialogue, as shown below.

Create Edit View
Create Edit View

In the Add View dialogue, keep the view name as Edit.

Select Edit Template and Student Model class from dropdown, as shown below.

Select Edit Template
Select Edit Template and Model

Click Add button to generate the Edit.cshtml view under /View/Student folder, as shown below.

                          @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              >                      

Please notice that Edit.cshtml includes the HtmlHelper method Html.BeginForm() to create the HTML form tag. Html.BeginForm sends a HttpPost request by default. This will display a Student data when you click an edit link in the student list view, as shown below.

Edit View

You can now edit the data and click on the Save button. The Save button should send the HttpPOST request because we need to submit the form data as a part of the request body as a Student object.

Step 4:

Now, write HttpPost action method Edit() to save the edited student object, as shown below. So, there will be two Edit() action methods, HttpGet and HttpPost action methods.

                          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)         {              //here, get the student from the database in the real application              //getting a student from collection for demo purpose              var              std = studentList.Where(s => s.StudentId == Id).FirstOrDefault();              return              View(std);         }          [HttpPost]              public              ActionResult              Edit(Student              std)         {              //update student in DB using EntityFramework in real-life application              //update list by removing old student and adding updated student for demo purpose              var              student = studentList.Where(s => s.StudentId == std.StudentId).FirstOrDefault();             studentList.Remove(student);             studentList.Add(std);              return              RedirectToAction("Index");         }     } }                      

In the above example, the HttpPost Edit() action method requires an object of the Student as a parameter. The Edit() view will bind the form's data collection to the student model parameter because it uses HTML helper methods @Html.EditorFor() for each properties to show input textboxes. Visit Model Binding section to know how MVC framework binds form data to action method parameter.

After updating the data in the DB, redirect back to the Index() action method to show the updated student list.

In this way, you can provide edit functionality using a default scaffolding Edit template.

How To Create Form In Mvc

Source: https://www.tutorialsteacher.com/mvc/create-edit-view-in-asp.net-mvc

Posted by: coxduccies.blogspot.com

0 Response to "How To Create Form In Mvc"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel