You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blazor中使用HTML属性?获取datalist的realvalue值

获取datalist自定义realvalue属性的值(Blazor场景)

由于Blazor无法直接通过input的change事件获取对应datalist选项的自定义属性,需要借助JavaScript互操作来实现,具体步骤如下:

1. 调整页面元素

给input添加ID和change事件绑定,保留原有datalist结构:

<input type="text" id="targetInput" list="list1" @onchange="GetRealValue" />
<datalist id="list1">
    <option realvalue="1">Option1</option>
    <option realvalue="2">Option2</option>
    <!-- 更多超1000条选项 -->
</datalist>

2. 编写JavaScript函数

在项目wwwroot/js/site.js(或页面内<script>标签)中添加匹配逻辑,提取realvalue:

window.getDatalistRealValue = function(inputId) {
    const input = document.getElementById(inputId);
    const datalist = document.getElementById(input.list.id);
    // 匹配输入值对应的选项
    const matchedOption = Array.from(datalist.options).find(opt => opt.textContent.trim() === input.value.trim());
    return matchedOption ? matchedOption.getAttribute('realvalue') : null;
};

3. Blazor代码中调用并接收值

在@code块注入IJSRuntime,调用JS函数获取真实值:

@inject IJSRuntime JS

private string list1value;

private async Task GetRealValue()
{
    var realValue = await JS.InvokeAsync<string>("getDatalistRealValue", "targetInput");
    if (realValue != null)
    {
        list1value = realValue;
        // 此处执行与数据库交互的逻辑,如提交、查询等
    }
    else
    {
        // 处理用户输入非选项值的情况,比如提示或清空
    }
}

注意事项

  • 确保datalist中每个option的文本内容唯一,避免匹配错误的realvalue
  • 若用户手动输入datalist外的内容,realValue会返回null,需根据业务需求处理该场景

内容的提问来源于stack exchange,提问作者HJ Y

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:12:48