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

Blazor中如何将输入文本框绑定到字典的键?

在Blazor中绑定输入框到字典键的实现方法

直接绑定字典的Key属性行不通——因为字典的键是不可变的,修改Key不会自动同步到字典本身。正确的做法是借助临时变量,再通过逻辑操作字典完成键的替换,具体实现如下:

实现思路

  1. 用临时字符串变量绑定输入框,而非直接绑定字典项的Key
  2. 触发更新时(比如点击按钮或输入框值改变),执行以下操作:
    • 取出旧键对应的模型值
    • 从字典中删除旧键
    • 用新键将模型值重新加入字典
    • 同步临时变量和当前选中项(避免输入框显示异常)

完整代码示例

组件变量定义

// 替换成你实际使用的模型类型
public class KeywordModel
{
    // 你的模型属性示例
    public string Content { get; set; } = string.Empty;
}

// 字典实例
private Dictionary<string, KeywordModel> Keywords = new()
{
    { "Name1", new KeywordModel { Content = "一些值" } },
    { "Name2", new KeywordModel { Content = "更多值" } }
};

// 当前正在编辑的键值对
private KeyValuePair<string, KeywordModel>? _currentKeyword;
// 绑定输入框的临时键名
private string _tempKey = string.Empty;

页面 Razor 代码

@foreach (var keyword in Keywords)
{
    <div style="margin: 10px 0;">
        <input type="text" 
               name="identifier" 
               @bind="@_tempKey" 
               @onfocus="() => SelectKeyword(keyword)"
               required/>
        <button @onclick="UpdateKey" style="margin-left: 8px;">更新键名</button>
    </div>
}

@code {
    // 选中字典项时初始化临时变量
    private void SelectKeyword(KeyValuePair<string, KeywordModel> keyword)
    {
        _currentKeyword = keyword;
        _tempKey = keyword.Key;
    }

    // 执行字典键更新逻辑
    private void UpdateKey()
    {
        if (_currentKeyword == null || string.IsNullOrWhiteSpace(_tempKey))
            return;

        // 新键与旧键相同,无需操作
        if (_tempKey.Equals(_currentKeyword.Value.Key, StringComparison.Ordinal))
            return;

        // 处理新键已存在的情况(可根据需求调整)
        if (Keywords.ContainsKey(_tempKey))
        {
            Console.WriteLine("该键名已存在,请更换");
            return;
        }

        // 取出旧键对应的模型
        var model = _currentKeyword.Value.Value;
        // 删除旧键
        Keywords.Remove(_currentKeyword.Value.Key);
        // 添加新键和模型
        Keywords.Add(_tempKey, model);
        // 更新当前选中项
        _currentKeyword = new KeyValuePair<string, KeywordModel>(_tempKey, model);
    }
}

额外说明

  • 若想自动触发更新(无需点击按钮),可以把@onclick换成@onchange="UpdateKey",但建议添加防抖逻辑,避免频繁修改字典
  • 新键重复的处理逻辑可根据业务需求调整,比如覆盖原内容、弹出提示或拒绝操作

内容的提问来源于stack exchange,提问作者Ayushi Amin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:16:13