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…".
3. Name the class "Employee" and click on the "Add" button.
4. In the employee class create employee properties like EmployeeId, FirstName, LastName and so on.
5. Now add a controller. Right-click on "Controllers" then select "Add" >> "Controller…".
6. Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button.
7. Name the controller as in the following:
8. In the Index action result method:
- Create a list of employees with some dummy employee details
- Assign a list to ViewData.Model
9. Now add a view. Right-click on the "Index" action method and select "Add View…".
10. 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.
11. It will automatically create a view from the model.
12. 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.
13. 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.
14. To add a view for the "Create" method, right-click on the "Create" action result method and select "Add View…".
15. 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.
16. It will automatically create a view from the model.
17. Get the value of the employee through its object and store it in a variable so that we can verify the posted data.
18. Now run the project and it will show the list of employees. By default it runs an Index action method of the Employee controller.
19. 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.
20. 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.
<<
Strongly Typed View List Sample in MVC: Day 24