0

Is it possible to access more than one IViewComponentResult method in a single ViewComponent Class? I seem to be able to create more then one method with each referencing their own View, but I have been unable to find a way to reference the individual methods within the class from a razor view.

public class PageHeaderViewComponent: ViewComponent
{
    public IViewComponentResult Header(LayoutModel layoutModel)
    {
        return View("Header", layoutModel);
    }

    public IViewComponentResult PageHeaderUpper(LayoutModel layoutModel)
    {
        return View("PageHeaderUpper", layoutModel);
    }

}
0

1 Answer 1

1

I suggest you can pass a parameter to Invoke method to conditionally return different view:

public class PageHeaderViewComponent : ViewComponent
{
    public IViewComponentResult Invoke(LayoutModel layoutModel,string name)
    {
        if(name=="header")
        {
            return View("Header", layoutModel);
        }
        else
        {
            return View("PageHeaderUpper", layoutModel);
        }
    }
}

You can invoke the view components like below in main view:

@await Component.InvokeAsync(typeof(PageHeaderViewComponent), new { LayoutModel= new LayoutModel() , name = "header" })
@await Component.InvokeAsync(typeof(PageHeaderViewComponent), new { LayoutModel= new LayoutModel() , name = "aaa" })

View Components location:

enter image description here

Besides, you can also use the property in LayoutModel as the condition.

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.