简体   繁体   中英

How to bind object to <select> option in Blazor?

I have the following dropdown menu:

public class object {
    public other_object apple {get; set;}
    ...
    public string stuff {get; set;}
    ...
}

public class other_object {
    public string id {get; set;}
    public string name {get; set;}
}

<select class="custom-select" @bind="@object.apple">
     <option value="@object.apple">@object.apple.name</option>
     ...
</select>

I want to bind the select to an object, but only want to display some attribute of that object. This will give me the error:

System.InvalidOperationException: The type 'other_object' does not have an associated TypeConverter that supports conversion from a string. Apply 'TypeConverterAttribute' to the type to register a converter.

Is this possible to do? I'm not really sure how the type converter thing works.

You cannot bind to other_object you can bind to a string property of other_object or use a TypeConverterAttribute to convert your other_object to a string.

Your code can be :

<select class="custom-select" @bind="@_selected.id">
     <option value="@object.apple.id">@object.apple.name</option>
     ...
</select>
@code {
    private other_object _selected = new other_object();
    ...
}

You can do it like this in case for any reason you need the object to be created here:

<InputSelect @bind-Value="@object.apple.id" @onchange="@((args) => @object.apple = new other_object { id = (int)args.Value })" class="form-control">
      <option value="@object.apple.id">@object.apple.name</option>                        
</InputSelect>

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