passing parameters from razor page to a razor component (objects are null, value types ok)

67 Views Asked by At

I am testing razor component with asp.net core 8 web app that uses razor pages. So my razor component in .razor file is

@code {
[Parameter]
public AssetVm? Asset { get; set; }

[Parameter]
public List<SelectListItem>? AssetTypes { get; set; }


[Parameter]
public int Test { get; set; }
}

<h3>Component1 from .razor file</h3>

@{
    var asset = Asset  ?? new AssetVm();
 }
 <select id="select2" asp-items="@AssetTypes" class="form-control"></select>

I use above component from a razor page as below

@(await Html.RenderComponentAsync<Component1>(RenderMode.ServerPrerendered, new { Asset = asset, AssetTypes = assetTypes, Test = 2 }))

The problem is only the Test property value gets passed. Both Asset and AssetType parameters are null. If I put a breakpoint at the razor page before await Html.RenderComponentAsync, values are there. I cannot figure out what I am doing wrong here to miss objects but get primitives passed properly.

According to this above code should work.

1

There are 1 best solutions below

0
Qiang Fu On BEST ANSWER

SelectListItem and <select .. asp-items="xxx"> not work in blazor component. I can only got "select" highlighted as green when in a cshtml with @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers. You could try below to use select in blazor component:
Component1.razor

<h3>Component1</h3>
@{
    var asset = Asset ?? new AssetVm();
}
@Asset.Name
<select >
    @foreach (var item in AssetTypes)
    {
        <option value="@item">@item</option>
    }
</select>
@Test

@code {
    [Parameter]
    public AssetVm? Asset { get; set; }

    [Parameter]
    public List<string> AssetTypes { get; set; } 

    [Parameter]
    public int Test { get; set; }
}

Test.cshtml

@page
@using BlazorApp114
@using BlazorApp114.Components.Pages
@model BlazorApp114.Pages.TestModel
@{
    var asset = new AssetVm() { Name = "Tom" };
    var assetTypes = new List<string>()
            {
                "car","property","portfolio"
            };
}
@(await Html.RenderComponentAsync<Component1>(RenderMode.ServerPrerendered, new { Asset = asset, AssetTypes = assetTypes, Test = 2 }))

Test result
enter image description here