Dot Net For All

Editing data in ASP.NET MVC with HttpPost

Editing the data in ASP.NET MVC

In my previous article I have shown how we can create an application to display a data collection in the ASP.NET MVC application. The beauty of ASP.NET MVC is that it takes care of all the plumbing and binding of the Model and View by itself but we should be aware of what is happening. This article is in continuation of the previous article. In this article we will see how we can Edit the data which we have created in the last application with code examples and we will learn about the HTML helpers and how they can be helpful in creating web application.


Now we start by creating a view for the Edit actions. Right click on Edit method with one parameter in the Student.cs controller and create a new View(by Clicking Add View..) as shown in the below two figures.

Figure 1

Figure 2

and change the code of the Edit method as shown in the Figure 1. We are passing an instance of the retrieved student to the view. As we done with these steps of creating a view for the Edit Student we will click the Add button on the Figure 2. Now we can see a new Edit.cshtml file in the Views > Student folder in the project.

Now run the project and go to the Student Details page by clicking on the Student Info Link on the top of the page. In this page click on any of the “Edit” link present against all the rows. I have clicked on the Edit present for the Vikram and we should be able to see the below page.

Now before preceding further for the article I will explain about a very important feature of asp.net mvc named HTML helpers by dissecting the above page.

HTML Helpers in ASP.NET MVC

After opening the above page in the browser and pressing F12 key and check the HTML produced I should be able to see the below figure.

Figure 4

 

which is generated by the .cshtml of the Edit view which is shown below code.

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

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

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

In the above code we can see that we are using @HTML property very frequently.

HTML is a property of ViewPage base class. We can say it is a property that a view inherits which can be used to create inputs, validation messages, labels , links and forms.

@HTML.EditorFor is an intelligent method which based on the type of the property of the model class creates the desired control, like for the string property it will create an textbox while for the boolean property it will create an checkbox.

Some of the highlights of the Edit Form

The HTML.BeginForm() will begin designing of the form and it will show the action from which we came from but set the method as POST so whenever the save button is clicked on the form the data is sent back to the controller to the same URL which is present in Action as seen in pointer 1 in  Figure 4.

As we come down a little bit we can see the HTML.HiddenFor() which will generate the HTML with input tag and type=Hidden which will be used to store the StudentID field which will not be shown to the user present as shown in pointer 2.

Further down we can see the @HTML.LabelFor() for which will generate the label for the field LastName as shown in pointer 3.

Down we can see the @HTML.EditorFor which is used to have the editable input fields which will take the input based on the type of the property as shown in the Pointer 4. Here it has generated input control for String as well as for number types which have an validation if we enter any alpha numeric values.

Now if we click on the save button to save the data and as I have told that the request from this page will be of POST(Check various HTTP Verbs here) type that is why it will go to the below code and not the other Edit which was used to get the data, and as shown in the below code I have received the student from the collection which I want to update and passed the object to the TryUpdateModel() method which will go through a process known as model binding and in fact model binding happens every time we have a parameter in action method. Model binding is what ASP.NET mvc does when it goes out and it looks in the request and try to find things to move into an object for you.

 // POST: ViewStudents/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                var editedStudent = studentList.Where(item => item.StudentID == id).Single();
                if(TryUpdateModel(editedStudent))
                {
                    //here the logic to save data in data source will come
                    return RedirectToAction("Index");
                }

                return View(editedStudent);
            }
            catch
            {
                return View();
            }
        }

When we have id parameter in the edit action the model binder in the ASP.NET MVC will find that ID which is StudentID in out case and move in to that for us to the Edit method.
What the TryUpdateModel will do is that it will try to look for each and every property of the model class and check for the corresponding field in the form data (e.g. FirstName in the figure 5 below) and move the updated data for that control to the controller action

 

Figure 5

and if the data is validated it will update it in the object and we can save it in the data source as shown in the code and redirect back to the Index view which will help us view the updated data on the screen.

If there is some problem in saving the data we return to the same Edit view.

This all happened because of the HTML helpers which will be able to create the controls with same id as that of property in the Model class.

Once the data is updated we can see the updated data in the View.

This was aticle which I have written to give an understanding of how the Editing of data works and how the controls are created with the help of HTML helpers.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview