1

I have a Razor Page where I include one view component which is basically a simple <select>. The intention is to use this component for reusing the logic behind a data filter.

The Default.cshtml file is like here below, the scripts tag helper for on-content-loaded is from here.

    @model SomeNamespace.UserNetworksSelectorModel
    @inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer Localizer

    <form method="get">
        <select asp-for="@Model.NetworkId" asp-items="@Model.NetworkItems" class="form-control user-network-selector"></select>
    </form>

    <script type="text/javascript" on-content-loaded="true">
        $(function () {
            $('.user-network-selector').change(function () {
                this.form.submit();
            });
        })
    </script>

The model has the properties public IList<SelectListItem> NetworkItems { get; set; } and public int NetworkId { get; set; } (not included here for simplicity).

In the page I include the view component using the tag helper <vc:user-networks-selector></vc:user-networks-selector>, similar to @await Component.InvokeAsync(typeof(SomeNamespace.ViewComponents.UserNetworksSelector)).

My question is: how can I access, from methods in the PageModel, the status in the view component? I'm interested in accessing the values of properties NetworkItems and NetworkId of its model.

Is it a bad practice to use view components like this?

V.Lorz
  • 293
  • 2
  • 8
  • Can you explain more detail about "access a View Component's property from a Razor Page"? Which View Component's property you want to access? Generally, when using View Component, we use it to render data on the main page: we will pass the parameter from the main view, and then filter data based on the parameter in the View Component, after that render results in the main page. So, I'm not sure about access the view component's property in the razor page, please explain more detail about it. If possible, can you share a sample via Github or Onedrive? Then we can work together to figure it out. – Zhi Lv Jun 17 '21 at 08:15
  • In the View Component I have included one `` according to one query parameter, it also makes a page GET submit when the selection changes, setting then a new value in the query parameter. I think the component could have one property `SelectedItemId`, for representing the selected item, that could be read from the main page. This is where I think I'm wrong as the component would do more than just rendering some content. – V.Lorz Jun 17 '21 at 08:34
  • @V.Lorz did you get an answer to this? I'm looking to do the same thing... – Jack Fox May 08 '23 at 01:27
  • I did not, sorry. – V.Lorz May 09 '23 at 07:02

0 Answers0