Strongly Typed Views in Asp.net Core

Strongly Typed Views in Asp.net Core
In ASP.NET Core MVC, a strongly typed view is a view that is associated with a specific model class. This means that the view has direct access to the properties and methods of that model, providing compile-time type checking and IntelliSense support within the view.
 
The @model Directive
The @model directive is used at the top of a view to specify the model type for that view. For example, @model Person indicates that the view expects to work with data of the Person class.
 
 
When to Use Strongly Typed Views
Complex Data: When your view needs to display or interact with complex data structures that have multiple properties or relationships.
Type Safety: When you want to catch type-related errors during development, rather than at runtime.
IntelliSense: When you want the full power of Visual Studio’s IntelliSense to help you code faster and with fewer errors.
Refactoring: When you need to change the model, strongly typed views make it easier to update the corresponding views automatically.
 
Best Practices
Use View Models: Instead of directly passing your business models to views, create specialized view models tailored to the data needed by each view. This helps keep your views clean and focused.
Naming Conventions: Follow standard naming conventions for your view models (e.g., ProductViewModel, OrderDetailsViewModel).
Keep Views Simple: Views should primarily focus on presentation logic. Avoid complex business logic within views.
Partial Views: Leverage partial views for reusable components, passing view models to them as needed.
Leverage Tag Helpers: Explore the use of Tag Helpers, which provide a more HTML-friendly way to interact with your models in views.
 
Code:
Controller (HomeController.cs)
// …
[Route(“home”)]
[Route(“/”)]
public IActionResult Index()
{
    List<Person> people = new List<Person>()
    {
        new Person() { Name = “John”, DateOfBirth = DateTime.Parse(“2000-05-06”), PersonGender = Gender.Male},
        new Person() { Name = “Linda”, DateOfBirth = DateTime.Parse(“2005-01-09”), PersonGender = Gender.Female},
        new Person() { Name = “Susan”, DateOfBirth = null, PersonGender = Gender.Other}
    };
 
    return View(“Index”, people); // Pass the ‘people’ list as the model
}
 
[Route(“person-details/{name}”)]
public IActionResult Details(string? name)
{
    // … (Retrieve the person based on the name) …
    Person? matchingPerson = people.Where(temp => temp.Name == name).FirstOrDefault();
    return View(matchingPerson); // Pass a single ‘Person’ object as the model
}
Both action methods pass the model(s) to the view using return View(model).
 
 
View (Index.cshtml)
@using ViewsExample.Models
@model IEnumerable<Person>  // Indicates that the model is a collection of Person objects
 
<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.appTitle</title>
    </head>
<body>
    <div class=”page-content”>
    <h1>Persons</h1>
 
    @foreach (Person person in Model)
    {
        <div class=”box float-left w-50″>
            <h3>@person.Name</h3>
            <table class=”table w-100″>
                <tbody>
                <tr>
                    <td>Gender</td>
                    <td>@person.PersonGender</td>
                </tr>
                <tr>
                    <td>Date of Birth</td>
                    <td>@person.DateOfBirth?.ToString(“MM/dd/yyyy”)</td>
                </tr>
                </tbody>
            </table>
            <a href=”/person-details/@person.Name”>Details</a>
        </div>
    }
    </div>
 
</body>
</html>
This view iterates over the Model (which is a list of Person objects) using a foreach loop. Inside the loop, it accesses the properties of each Person object directly (e.g., @person.Name, @person.PersonGender) thanks to strong typing.
 
 
View (Details.cshtml)
@using ViewsExample.Models
@model Person // Indicates that the model is a single Person object
 
<!DOCTYPE html>
<html>
<head>
    <title>Person Details</title>
    </head>
<body>
    <div class=”page-content”>
        <h1>Person Details</h1>
        <div class=”box”>
            <h3>@Model.Name</h3>
            <table class=”table w-100″>
                <tbody>
                <tr>
                    <td>Gender</td>
                    <td>@Model.PersonGender</td>
                </tr>
                <tr>
                    <td>Date of Birth</td>
                    <td>@Model.DateOfBirth?.ToString(“MM/dd/yyyy”)</td>
                </tr>
                </tbody>
            </table>
        </div>
        <a href=”/home”>Back to persons</a>
    </div>
</body>
</html>

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply