简体   繁体   English

Blazor 数据绑定两个值到选择列表

[英]Blazor data binding two values to selectlist

I can easily bind one value to my model, but what if I want to bind two or more?我可以轻松地将一个值绑定到我的 model,但是如果我想绑定两个或更多呢?

Sample code, tried to bind to the complex object but it fails.示例代码,尝试绑定到复杂的 object 但失败。

Component:零件:

 <select id="myClassId" @onchange="SelectionChanged" class="form-control">
                            <option value=""></option>
                            @foreach (var myObject in myClassList)
                            {
                                <option value="@myObject">@myObject.AccountName</option>
                            }
                        </select>

Code代码

 void SelectionChanged(ChangeEventArgs e)
    {
        Console.WriteLine(((MyClass)e.Value).AccountId);
        Console.WriteLine(((MyClass)e.Value).AccountName);

    }

UPDATE:更新:

Ended up doing this.最终这样做了。 Probably not the most elegant solution, but I'm not sure if there are other more "supported" ways.可能不是最优雅的解决方案,但我不确定是否还有其他更“支持”的方式。

<select id="myClassId" @onchange="SelectionChanged" class="form-control">
                            <option value=""></option>
                            @foreach (var myObject in myClassList)
                            {
                                <option value="@myObject.AccountId;@myObject.AccountName">@myObject.AccountName</option>
                            }
                        </select>

 void SelectionChanged(ChangeEventArgs e)
    {
        var accountId = e.Value.ToString().Split(";")[0];
        var accountName = e.Value.ToString().Split(";")[1];
        Console.WriteLine(accountId);
        Console.WriteLine(accountName);
    }

The value of a select is a string. select 的值是一个字符串。 That is a fundamental limitation of the HTML, and has nothing to do with Blazor.这是 HTML 的基本限制,与 Blazor 无关。 You cannot use an object.您不能使用 object。 Your best bet here is to assign an id or some other uniquely identifying value, and then in your onchange handler, look up the actual object you want to assign using that value.您最好的选择是分配一个 id 或其他一些唯一标识值,然后在您的 onchange 处理程序中,使用该值查找您要分配的实际 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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