Home > Enterprise >  Pass multiple parameters to ViewComponent in ASP.NET MVC
Pass multiple parameters to ViewComponent in ASP.NET MVC

Time:04-19

I want to pass multiple parameters to a view component in ASP.NET MVC using C#.

So I did this:

public IViewComponentResult Invoke(Ordering ordering, InvokeRequest invokeRequest)
{
    var productList = _context.GetProductForSiteService
                              .Execute(invokeRequest.ordering, invokeRequest.Searchkey, invokeRequest.page, invokeRequest.pageSize, null).Data;
     
    return View(viewName: "GetProducts", productList);
}

public class InvokeRequest
{
    public Ordering ordering { get; set; }
    public string Searchkey { get; set; }
    public int page { get; set; } = 1;
    public int pageSize { get; set; } = 20;
}

and in the view, I have:

 @await Component.InvokeAsync("GetProducts", new  { Ordering=Ordering.NotOrder, Searchkey="", page=1, pageSize=20 })

but the value of the InvokeRequest in Invoke method is always null, how can I pass multiple parameter to a ViewComponent?

CodePudding user response:

The properties of the object you pass don't match with your Invoke method signature.
From the documentation

An Object with properties representing arguments to be passed to the invoked view component method.

The object to pass needs the properties ordering and invokeRequest.

@await Component.InvokeAsync("GetProducts", 
    new { 
        ordering = Ordering.NotOrder, 
        invokeRequest = new InvokeRequest { ordering = Ordering.NotOrder, Searchkey = "", page = 1, pageSize = 20 }
    })

Since that InvokeRequest also contains an ordering property, you might consider to leave that out of the components Invoke method signature.

public IViewComponentResult Invoke(InvokeRequest invokeRequest)

The call would than look like

@await Component.InvokeAsync("GetProducts", 
    new InvokeRequest { ordering = Ordering.NotOrder, Searchkey = "", page = 1, pageSize = 20 }
    )
  • Related