Strongly Typed View Components in Asp.net Core MVC

Strongly Typed View Components in Asp.net Core MVC
Just like strongly typed views, strongly typed view components are associated with a specific model class using the @model directive. This model class, often referred to as a “view model,” provides a structured way to pass data from the view component to its corresponding view. The primary benefit is enhanced type safety and improved code maintainability.
 
Benefits of Strongly Typed View Components
Type Safety: Catches errors during development due to mismatched data types or property names, as the Razor engine enforces type checking based on your model class.
IntelliSense: Enhances productivity by providing code completion and suggestions for model properties directly within the Razor view. This leads to fewer typos and faster development.
Refactoring: Simplifies the process of updating views when your model changes. Since the view is strongly typed, renaming or modifying properties in the model will automatically update the references in the view.
Clarity and Readability: Makes your code more self-documenting by clearly defining the data structure expected by the view component.
 
Implement Strongly Typed View Components
Create a View Model: Define a class that represents the data you want to pass to your view component. This class should contain all the necessary properties that the view component will use to render its output.
Use @model in the View: In your view component’s Razor view file (e.g., Default.cshtml), use the @model directive to specify the view model class.
Return the Model from InvokeAsync: In your view component’s InvokeAsync method, create an instance of your view model, populate it with the required data, and return it using View(model).
 
Example
PersonGridModel.cs (View Model)
public class PersonGridModel
{
    public string GridTitle { get; set; }
    public List<Person> Persons { get; set; }
}
This model will be used to represent the data passed from the view component to the view.
 
GridViewComponent.cs
// ViewComponent
public class GridViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        PersonGridModel personGridModel = new PersonGridModel()
        {
            GridTitle = “Persons List”,
            Persons = new List<Person>() {
                new Person() { PersonName = “John”, JobTitle = “Manager” },
                new Person() { PersonName = “Jones”, JobTitle = “Asst. Manager” },
                new Person() { PersonName = “William”, JobTitle = “Clerk” },
            }
        };
        return View(“Sample”, personGridModel);
    }
}
The method now creates a PersonGridModel object, populates it, and passes it as the second argument of the View() method.
 
Views/Shared/Components/Grid/Sample.cshtml
@model PersonGridModel
 
<div class=”box”>
    <h3>@Model.GridTitle</h3>
    <table class=”table w-100″>
        <thead>
            <tr>
                <th>Sl. No</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (Person person in Model.Persons)
            {
                <tr>
                    <td>@person.PersonName</td>
                    <td>@person.JobTitle</td>
                </tr>
            }
        </tbody>
    </table>
</div>
 
@model PersonGridModel: This specifies that the view is strongly typed and expects an object of type PersonGridModel.
Accessing Properties: The view directly accesses properties of the Model object like Model.GridTitle and Model.Persons.
 

Comments

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

Leave a Reply