2

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();
    }
}
4
  • You may want to create a class that has an int property: id and take that as a parameter in the component instead of just an int. Commented Mar 19, 2021 at 13:48
  • Do you mean to create a class by type as a model in which there will be an Id property? And pass it to the View Component? Commented Mar 19, 2021 at 13:58
  • Yes, that is what you are passing right now, but the vc is expecting just an int. But have tried just passing id instead of new {id} ? Commented Mar 19, 2021 at 14:03
  • Forget what I said, look at the answer below Commented Mar 19, 2021 at 14:06

1 Answer 1

7

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();
    }
}
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.