View Components with Parameters in Asp.net Core MVC

View Components with Parameters in Asp.net Core MVC
While view components can function without parameters, passing parameters to them significantly enhances their flexibility and reusability. Parameters allow you to customize the behavior and output of a view component based on data provided by the calling view or controller. This makes view components more dynamic and adaptable to different scenarios within your application.
 
Pass Parameters to View Components
Define Parameters in InvokeAsync: In your view component class, define the parameters that you want to receive within the InvokeAsync (or Invoke) method. These parameters will become part of the method’s signature.
Pass Arguments When Invoking: When invoking the view component using @await Component.InvokeAsync(“ViewComponent Name”, arguments) or the <vc:grid> tag helper, pass an anonymous object containing the parameter values. The property names in the anonymous object must match the parameter names in the InvokeAsync method.
 
Example
GridViewComponent.cs
public class GridViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(PersonGridModel grid) 
    {
        return View(“Sample”, grid);
    }
}
Parameter: The InvokeAsync method now takes a parameter of type PersonGridModel. This means the view component expects to receive a model containing grid data when it’s invoked.
 
Views/Home/Index.cshtml
@{
    PersonGridModel personGridModel = new PersonGridModel() { /* … (data initialization) … */ };
}
 
@await Component.InvokeAsync(“Grid”, new { grid = personGridModel })
 
@{
    PersonGridModel personGridModel2 = new PersonGridModel() { /* … (different data initialization) … */ };
}
@await Component.InvokeAsync(“Grid”, new { grid = personGridModel2 })
Two instances of PersonGridModel are created and passed as an argument to the view component when invoking it.
 
Views/Home/About.cshtml
@{
    PersonGridModel personGridModel = new PersonGridModel() { /* … (data initialization) … */ };
}
 
<vc:grid grid=”personGridModel”></vc:grid>
 
Tag Helper Usage: The <vc:grid> tag helper is used here to invoke the view component. The grid attribute is set to the personGridModel, passing the model data to the view component.

 

Comments

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

Leave a Reply