Strongly typed view is a nice feature of
ASP.NET MVC. We can access model properties on that view using strongly typed view and we can bind views with any model.
Now let's create a Strongly Typed View List in MVC.
Step 1: Create a ASP.NET MVC application by selecting Empty Template and add Core Reference for MVC.
Step 2: Right click on your Model Folder and add a new Class File called 'Student.cs'.
Step 3 : Open your Student.cs file and create a Student property like RollNo, FirstName, LastName.
- public class Student
- {
- public int RollNo
- {
- get;
- set;
- }
- public string StudFirstName
- {
- get;
- set;
- }
- public string StudLastName
- {
- get;
- set;
- }
- }
Step 4: Right click on Controller and new Empty Controller from the Add Scaffold.
Step 5: Give a name to Controller like "StudentController."
Step 6: Open 'StudentController' file and create a list of Student, then assign RollNo, Name etc.
Finally assign the Stud Object to ViewData.Model.
- public ActionResult Index()
- {
- List<Student> stud = new List<Student>
- {
- new Student { RollNo=1, StudFirstName="Ankur", StudLastName="Mistry" },
- new Student { RollNo=2, StudFirstName="Rahul", StudLastName="Lad" }
- };
-
- ViewData.Model = stud;
-
- return View();
- }
Step 7: Now, right click on Index in Controller and click on Add View.
From the Add View dialog box, Select the ModelClass Student (WebApplication1.Models), Now from Template tab select 'List' as we are going to display model data in List and Click on Add.
It will create a Student View in View folder as per below screen. I have removed edit, delete, and create Link from here as we are just going to display the data.
Now run your application, it will display the Data of Students.
Summary
So there are two main benefits of strongly typed view here.
1. Intellisense support.
2. ViewModel will be automatically scaffolded.
So here in our example, when we create a View by selecting Template as List, our ViewModel is automatically scaffolded.
- <table class="table">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.RollNo)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.StudFirstName)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.StudLastName)
- </th>
- <th></th>
- </tr>
-
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.RollNo)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.StudFirstName)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.StudLastName)
- </td>
- <a href="#">@item.RollNo</a>
- </tr>
- }
-
- </table>
I hope you liked this article.
Read more articles on ASP.NET: