Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Graeme 4 posts 74 karma points
    Dec 30, 2022 @ 04:10
    Graeme
    0

    Using a ViewComponent with a Parameter

    I am trying to display a ViewComponent passing it a string parameter, but cannot get this to work. Instead of looking for MyViewComponent\Default.cshtml, if, for instance, I was to pass "FooBar" as the value of the parameter, it is looking for MyViewComponent\FooBar.cshtml. I assume Umbraco overrides the routing . The Umbraco documentation doesn't contain any reference to passing parameters to a ViewComponent. Would anyone be able to help me out with this?

  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Dec 30, 2022 @ 09:25
    Huw Reddick
    0

    Hi Graeme,

    This is what I do.

    method signature in ViewComponent class

    public async Task<IViewComponentResult> InvokeAsync(string qryUser, string Template, int pageSize)
    

    Calling ViewComponent in a view

    @await Component.InvokeAsync("ForumMembership",new {Template = "EditProfile",qryUser = Context.Request.Query["user"].ToString()})
    
  • Graeme 4 posts 74 karma points
    Dec 30, 2022 @ 10:17
    Graeme
    0

    Hi Huw,

    Actually I responded too early to your answer, and realized I still have the same problem. I assume the Template is the name of the ViewComponent .cshtml file, in my case Default. But if I call

    @await Component.InvokeAsync("MyViewComponent", new { Template = "Default", myParam = "FooBar" })
    

    I still get an error saying that

    The view 'Components/MyComponent/Foobar' was not found. The following locations were searched:
    

    followed by a list of the standard ViewComponent directories but looking for FooBar.cshtml in each case.

  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Dec 30, 2022 @ 12:01
    Huw Reddick
    0

    actually string Template is something I pass so that I can reuse the same viewcomponent class for different templates, it is not something passed by default and is not required for viewcomponents to work. It seems to me you are not creating yours correctly,

    If it is not finding your viewcomponent then it is possibly not named correctly your views should be in

    Views\shared\components\YOURVIEWCOMPONENTNAME\Default.cshtml

    I use the string Template so that I can do the following in my viewcomponent, and return whichever template I require

    return await Task.FromResult((IViewComponentResult)View(Template));
    

    What does the code for your viewcomponent look like?

Please Sign in or register to post replies

Write your reply to:

Draft