I need to pass some value to the View Component from the controller. I tried differently but it does not transmit. If I don't pass anything to the constructor then everything works fine, but when I try to pass it to the constructor it doesn't even call the ViewComponent
Controller:
[HttpGet]
public IActionResult AddToCart(int id)
{
return ViewComponent("Cart", new {id});
}
View Component:
public class CartViewComponent : Microsoft.AspNetCore.Mvc.ViewComponent
{
int gId;
public CartViewComponent(int id)
{
gId = id;
}
public IViewComponentResult Invoke()
{
return View();
}
}
Invoking a view component includes the following explanation:
The parameters will be passed to the
InvokeAsync
method.
This means you should move your id
parameter from the constructor to the Invoke
method:
public class CartViewComponent : Microsoft.AspNetCore.Mvc.ViewComponent
{
public IViewComponentResult Invoke(int id)
{
// Use id here.
return View();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.