我正在使用使用 razor 页面的 asp.net core 8 Web 应用程序测试 razor 组件。所以我的 .razor 文件中的 razor 组件是
@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>
我使用剃刀页面中的上述组件,如下所示
@(await Html.RenderComponentAsync<Component1>(RenderMode.ServerPrerendered, new { Asset = asset, AssetTypes = assetTypes, Test = 2 }))
问题是只有 Test 属性值通过了。 Asset 和 AssetType 参数均为 null。如果我在等待 Html.RenderComponentAsync 之前在剃刀页面放置断点,则值就在那里。我无法弄清楚我在这里做错了什么,错过了对象,但正确传递了原语。
根据this,上面的代码应该可以工作。
SelectListItem
和 <select .. asp-items="xxx">
在 blazor 组件中不起作用。当在 cshtml 中使用 @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
时,我只能将“选择”突出显示为绿色。
您可以尝试下面在 blazor 组件中使用 select :<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; }
}
测试.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 }))