Route data describes how the routing system handled the current request URL. Values captured from URL segments are available by name through RouteData.Values. A view component can read its RouteData property to adapt its output to the current request. section 8.1.3 section 24.5
Highlight the selected category
A navigation view component reads RouteData?.Values["category"] and assigns it to ViewBag.SelectedCategory. Its Razor view compares that value with each category to give the selected link a different button style. In a unit test, set ViewComponentContext.ViewContext.RouteData, assign Values["category"], invoke the component, and check its view data. section 8.1.3
Listing 8.10 Passing the selected category in the NavigationMenuViewComponent.cs file in the SportsStore/Components folder
using Microsoft.AspNetCore.Mvc;
using SportsStore.Models;
namespace SportsStore.Components {
public class NavigationMenuViewComponent : ViewComponent {
private IStoreRepository repository;
public NavigationMenuViewComponent(IStoreRepository repo) {
repository = repo;
}
public IViewComponentResult Invoke() {
ViewBag.SelectedCategory = RouteData?.Values["category"];
return View(repository.Products
.Select(x => x.Category)
.Distinct()
.OrderBy(x => x));
}
}
}
The navigation component reads the category route value before returning its category list to the view. section 8.1.3
Route data also supplies action arguments through model binding. For /controllers/Form/Index/5?id=1, the route supplies id = 5 and the query string supplies id = 1. The default binder finds the route value first, so the action receives 5. If the URL has no id segment, a query-string value can supply it instead. section 28.2
Vary output by routing pattern
A view component can check whether RouteData.Values["controller"] is present. The illustrated component returns “Controller Request” when it is and “Razor Page Request” otherwise. section 24.5

