1

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?

1 Answer 1

3

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 }
    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.