在blazor中选择框绑定

在blazor中选择框绑定

本文介绍了在blazor中选择框绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将模型中的"CountryId"绑定到blazor中SelectList的选定项的值.所有国家/地区项目都位于{CountryId,CountryName}对象之类的列表中.我这样做的代码如下:

I am trying to bind "CountryId" in the model to the value of a selected item of SelectList in blazor. All of the Country items come in a list like {CountryId, CountryName} object. I do the code like so:

    <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>

和代码块:

@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"
    };
}

但是这种执行在浏览器中给了我这个错误:

But this execution gives me this error in the browser:

在blazor中绑定<select>model.data的便捷方法是什么?感谢您的阅读!

What is the convenient way of binding <select> and model.data in blazor?Thanks for reading!

推荐答案

当我将<InputSelect>放在<EditForm Model="@model">..</EditForm >中并且您的数据绑定没有问题时,效果很好.

It works well when I put the <InputSelect> in a <EditForm Model="@model">..</EditForm >and there's no problem in your data binding.

尝试使用以下代码在csproj文件中设置<BlazorLinkOnBuild>false</BlazorLinkOnBuild>.

Try to use below code to set <BlazorLinkOnBuild>false</BlazorLinkOnBuild> in the csproj file.

<PropertyGroup>
   <BlazorLinkOnBuild>false</BlazorLinkOnBuild>
</PropertyGroup>

请参阅 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>

这篇关于在blazor中选择框绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:02