locked
How do I get route values from inside a View Component controller? RRS feed

  • Question

  • User-797886026 posted

    I have a View Component in _Layout.cshtml. My application has a route of /home/{id}. How can I get the id value in my URL route from the View Component controller?

    public class LayoutViewComponent : ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync()
        {
            //how do I get the value of {id} here?
    
            return View();
        }
    }
    Friday, April 7, 2017 7:29 PM

All replies

  • User1512245536 posted

    Hi! It is very easy. Just add the parameters as the InvokeAsync method arguments:

    public async Task<IViewComponentResult> InvokeAsync(int id)
    {
         return View();
    }

    So it is done the same way as in controllers.

    Friday, April 7, 2017 9:05 PM
  • User-797886026 posted

    Thanks for the reply. I wasn't sure how to to get the id from the route and pass it into the InvokeAsync call but I ended up being able to use

    ViewContext.RouteData.Values["id"];

    Thursday, April 13, 2017 12:05 AM
  • User1012756072 posted

    I have spent 3 hours to solve a similar problem until I have seen this comment... You saved me from spending another 3 hour or maybe more. Thanks from 2020.

    Wednesday, December 23, 2020 9:36 PM