To present data stored in your database to the user in an elegant and user-friendly way, use views. Views in ASP.NET are written in Hypertext Markup Language (HTML and CSS), along with some additional syntax to represent dynamically changing data.

The views generated map to your controller’s action methods. The Index() method has a view called Index.cshtml and Create() method has a view called Create.cshtml and so on.

Focus on those parts of views that allow you to take data from your models and display them to the user.

Importing model data into views

@model IEnumerable<<t>People.Models.User</t>> declared at the start of a view allows you to read different model class properties. In this case, you can read User classes’ properties and extract data accordingly.

Accessing model class properties

@Html.DisplayNameFor(model => model.Name) allows you to access the model classes’s property name and represent it into your view. The advantage of using this syntax instead of hardcoding a string is because the model might have an property name but a different display name. For example, the property PhoneNumber will be displayed as “Phone Number” because of Display attribute.

Iterating through data

If you wish to utilize some sort of a loop in your views that iterates through an entire table, use @foreach. The complete syntax will be: @foreach (var item in Model). Data per iteration is accessed from a variable called item.

Accessing data in each iteration

Data can be extracted by using item. which is followed by the property name. item.Name will provide you with names stored in your database from the Users table. The complete syntax for this functionality is: @Html.DisplayFor(modelItem => item.Name)

Calling action function

To call an action function of a controller, use asp-action followed by the function name. For example, asp-action="Edit" calls the Edit() function from the controller.

Passing data to action function

If you call an action function and you also wish to pass ID parameters, asp-route-id can be used. For example asp-route-id="@item.ID" will pass ID associated with item. Furthermore, item will contain an instance of data from each iteration of @foreach loop.

Code in action

Get hands-on with 1200+ tech skills courses.