Emb*_*yub 26 c# asp.net asp.net-core blazor
我试图将模型中的“CountryId”绑定到 blazor 中 SelectList 的选定项目的值。所有国家/地区项目都在一个列表中,如 {CountryId, CountryName} 对象。我这样做的代码是这样的:
<InputSelect @bind-Value="model.ByCountryId" class="form-control">
@if (model?.Countries != null)
{
@foreach (var cnt in model.Countries)
{
<option value="@cnt.Id">@cnt.Name</option>
}
}
</InputSelect>
Run Code Online (Sandbox Code Playgroud)
和代码块:
@code {
BrandModel model = new BrandModel();
protected override async Task OnInitializedAsync()
{
model = new BrandModel
{
Id = 19,
ByCountryId = 1,
Countries = new List<ent.Country>
{
new ent.Country { Id = 1, Name = "Azerbaijan" },
new ent.Country { Id = 2, Name = "Turkey" }
},
IsActive = true,
Name = "Brand"
};
}
Run Code Online (Sandbox Code Playgroud)
但是这个执行在浏览器中给了我这个错误:
blazor.webassembly.js:1 WASM:System.MissingMethodException:未找到类型“System.ComponentModel.ByteConverter”的构造函数。
绑定<select>和model.data在 blazor 中的便捷方式是什么?谢谢阅读!
Rya*_*yan 26
当我将<InputSelect>a放入<EditForm Model="@model">..</EditForm >并且您的数据绑定没有问题时,它运行良好。
尝试使用以下代码<BlazorLinkOnBuild>false</BlazorLinkOnBuild>在 csproj 文件中进行设置。
<PropertyGroup>
<BlazorLinkOnBuild>false</BlazorLinkOnBuild>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
参考https://github.com/aspnet/AspNetCore/issues/7784
更新:
使用<select>标签而不是<InputSelect>喜欢
<select @bind="model.ByCountryId">
@if (model?.Countries != null)
{
@foreach (var cnt in model.Countries)
{
<option value="@cnt.Id">@cnt.Name</option>
}
}
</select>
Run Code Online (Sandbox Code Playgroud)
小智 6
我没有尝试解决您的问题,因为有很多。相反,我编写了代码如何在选择元素中显示国家/地区列表,并检索选定的国家/地区代码或 ID。请看看我如何定义模型以及如何使用它。此代码适合与其他选择元素集成,形成级联下拉体验(选择国家后填充的城市列表等)。只需将代码片段复制到您的 Index.razor 文件并执行它...
<select class="form-control" @bind="@SelectedCountryID">
<option value=""></option>
@foreach(var country in CountryList)
{
<option value = "@country.Code"> @country.Name </option >
}
}
</select>
<p>@SelectedCountryID</p>
@code {
string selectedCountryID;
string SelectedCountryID
{
get => selectedCountryID;
set
{
selectedCountryID = value;
}
}
List<Country> CountryList = new List<Country>() { new Country ("USA", "United States"),
new Country ("UK", "United Kingdom") };
public class Country
{
public Country(string code, string name)
{
Code = code;
Name = name;
}
public string Code { get; set; }
public string Name { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)