Search code examples
c#asp.net-coreasp.net-core-viewcomponent

How can View Component be used to call PartialView by its name instead of loading default.cshtml


I wanted to load Partial Views based upon TopUserCount value which is received by argument. I have different PartialViews available to suffice this requirement. But seems View Component only loads Default.cshtml

something like this:

public IViewComponentResult Invoke(int TopUserCount)
{
    var items = GetUsers().OrderByDescending(u => u.Points).Take(TopUserCount);
    if(TopUserCount == 1) return View("customView1");
    if (TopUserCount == 2) return View("customView2");
    else
        return View(items);  //defaultView.cshtml
}

Solution

  • It is important to place the partial views at right folder structure. in this case under 'Views\ControllerName\Components\ViewComponentName'