【问题标题】:How to bind object to <select> option in Blazor?如何将对象绑定到 Blazor 中的 <select> 选项?
【发布时间】:2020-03-29 07:01:32
【问题描述】:

我有以下下拉菜单:

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>

我想将选择绑定到一个对象,但只想显示该对象的某些属性。这会给我错误:

System.InvalidOperationException:类型“other_object”不 有一个 支持从字符串转换的关联 TypeConverter。申请 'TypeConverterAttribute' 到注册转换器的类型。

这可能吗?我不太确定类型转换器的工作原理。

【问题讨论】:

  • 你能再分享一些代码吗?用这种方式分辨类型是不可能的..
  • 它们都是自定义对象。 other_object 里面有两个字符串。查看我刚刚发布的代码。
  • 类型仍然缺失
  • 什么类型? other_object 中的 name 和 id 是字符串,object 是对象的集合以及这里不需要的其他信息。
  • 检查..但这仍然需要更多代码..你是如何初始化东西的?现在的代码不可能工作。

标签: c# html blazor webassembly


【解决方案1】:

您不能绑定到other_object,您可以绑定到other_object 的字符串属性或使用TypeConverterAttribute 将您的other_object 转换为字符串。

您的代码可以是:

<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();
    ...
}

【讨论】:

【解决方案2】:

如果出于任何原因需要在此处创建对象,您可以这样做:

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

【讨论】:

    猜你喜欢
    • 2020-06-13
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多