简体   繁体   中英

Select box binding in blazor

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>

And code block:

@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.webassembly.js:1 WASM: System.MissingMethodException: Constructor on type 'System.ComponentModel.ByteConverter' not found.

What is the convenient way of binding <select> and model.data in Blazor?

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

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

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

Refer to https://github.com/aspnet/AspNetCore/issues/7784

Update:

Use <select> tag instead of <InputSelect> like

<select @bind="model.ByCountryId">
        @if (model?.Countries != null)
        {
            @foreach (var cnt in model.Countries)
            {
                <option value="@cnt.Id">@cnt.Name</option>
            }
        }
</select>

I did not try to solve your issues because there are many. Instead I composed code how you can display a list of countries in a select element, and retrieve the selected country code or ID. Please, see how I define a model and how it is used. This code is suitable to be integrated with other select elements to form cascading dropdown experience (a list of cities that is populated after selecting a country, etc.). Just copy the code snippet to your Index.razor file and execute it...

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

    }
}

<InputSelect> works for me In .NET 5. For every Inputs (text, number, date, select, checkbox etc) I use <EditForm> with Model .

<EditForm Model="item">
   <InputSelect @bind-Value="item.CountryId">
      <option value=""></option>
      @foreach (var c in countries)
      {
         <option value="@c.Id">@c.Name</option>
      }
   </InputSelect>
</EditForm>

For this example: ItemModel item has at least property CountryId and List<CountryModel> countries has at least properties int Id and string Name

There could be many problems why this can fall, I spent several hours finding out where I went wrong the first time I tried to do something like this.

1) You should check if the connation in database level configure correctly, for that here's a great description: https://www.learnentityframeworkcore.com/configuration/one-to-one-relationship-configuration

2) If all in order here, you should pass the list of countries to the view in the viewbag for this your create should look something like this:

// GET: Reservations/Create
public IActionResult Create()
{
    ViewData["Country"] = new SelectList(_context.Countries, "CountryID", 
    "CountryName");
    return View();
}

3) And your view should look like this:

<select id="Country" asp-for="Country" class="form-control">
    <option value="" selected disabled hidden>Choose country</option>
</select>

Hope this helps!

Working fine in Core 6 using API in blazor

       <InputSelect @bind-Value="patientCreateDTO.DoctorId" class="form- 
         control" id="doctorid">
        <option value="">--Select--</option>
        @foreach(var doctor in doctorslist)
        {
            <option value="@doctor.Id">@doctor.Doctor_name</option>
        }
    </InputSelect>

and here is the code

 private List<DoctorReadDTO> doctorslist = new();

protected override async Task OnInitializedAsync()
{
  

    var response = await dService.GetDoctor();
    if(response.Success)
    {
        doctorslist = response.Data;
       
    }
}
 
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM