Strongly Typed View Create Sample in MVC

Strongly Typed View Create Sample in MVC

In this article we will add an employee to a list of employees by creating a strongly typed view.

  1. Create a MVC project from the "Empty" template.
  2. Right-click on "Models", select "Add" >>"Class…".

2.jpg

Name the class "Employee" and click on the "Add" button.

3.jpg

In the employee class create employee properties like EmployeeId, FirstName, LastName and so on.

4.jpg

Now add a controller. Right-click on "Controllers" then select "Add" >> "Controller…".

5.jpg

Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button.

6.jpg

Name the controller as in the following:

7.jpg

In the Index action result method:

  - Create a list of employees with some dummy employee details
  - Assign a list to ViewData.Model

8.jpg

Now add a view. Right-click on the "Index" action method and select "Add View…".

9.jpg

Name the view as "Index".

  - Since we will show a list of employees, select "List" for the template.
  - From the model class drop down, select "Employee" as the model.
  - Click on the "Add" button.

10.jpg

It will automatically create a view from the model.

11.jpg

Remove the edit, details and delete links from the bottom of the table since we only want to display a list of employees and create a new employee link.

12.jpg

Now add two action result methods to the employee controller with the same name, one is for HttpGet and another one is for HttpPost. In the HttpPost "Create" method pass an Employee class object as a parameter. When we press the submit button it will call this HttpPost method.

13.jpg

To add a view for the "Create" method, right-click on the "Create" action result method and select "Add View…".

14.jpg

Name the view as "Create".

  - Since we will show a create form for an employee, select "Create" for the template.
  - From the model class drop down, select "Employee" as the model.
  - Click on the "Add" button.

15.jpg

It will automatically create a view from the model.

16.jpg

Get the value of the employee through its object and store it in a variable so that we can verify the posted data.

17.jpg

Now run the project and it will show the list of employees. By default it runs an Index action method of the Employee controller.

18.jpg

Click on the "Create New" link and it will show the Create employee form. Fill in the appropriate data and click on the "Create" button.

19.jpg

By debugging, we can verify that the posted data and the data that we receive in the object are the same. You can now save this employee detail in the created list or in the database as required.

20.jpg