MVC: Adding a Record Page

Adding Data

Setting Up The Controller

To add data to the table requires two Actions in the controller. The first will display the HTML form to allow a new record to be added, the second Action will add the values submitted to the database. Both these Actions will have the same name but are differentiated by having attributes of HttpGet for the controller showing the blank form, and HttpPost for the Action to insert the data.

The Iintial Form

In the Controllers/HomeController add the first action as follows:

CONTROLLER: Controllers/HomeController.cs

This is a straight forward call to the View. Now create the view.

VIEW: Views/Home/AddFilm.cshtml

There some now be a form to input a new film when tested.

Action to Handle Form Submission

In the controller now add a second Action this time to receive data from the form. The form has a method of post so the second controller will have the httpPost attribute. We can also use the same method name for the action as it will differ from the httpGet version by also taking a parameter. The parameter is the Film model from the form.

CONTROLLER: Controllers/HomeController.cs

The new data is added to the table via the Add method of DbContext and the SaveChanges method of the DbSet. The controller then redirects to the AllFilms Action and thus the AllFilms View.