c# - @onkeypress 没有获取文本输入框的更新值?

标签 c# razor blazor blazor-server-side

我有以下代码。

<input id="search" type="text" @bind="Search" @onkeypress="SearchChanged" />
@code {
    string Search;

    void SearchChanged() 
    { 
        var s = Search; // Search is always one character behind
    }
}

在文本框中输入将触发函数 SearchChanged。但是,它得到的值始终是键入文本之前的一个字符。比如在SearchChanged中设置断点,

Typed Value of  Search
===== ================
a     null
ab    a
abc   ab
abcd  abc

BTW, the @onkeypress doesn't work in Internet Browser?


Tried to change the code to

<input id="search" type="text" @bind="Search" />
@code {
    string search;
    string Search 
    {
        get { return search; }
        set {
            search = value;
            ResultList = GetNewList(search).Result.ToList(); 
        }
    }

    void SearchChanged() 
    { 
        var s = Search; // Search is always one character behind
    }
}

我在 set { } 中设置了一个断点,但是,在输入文本框时,断点只命中了一两次?

最佳答案

您正在寻找@bind-value:event:

<input id="search" 
       type="text" 
       @bind-value="Search" 
       @bind-value:event="oninput"
/>

@code {
  string search;
  string Search 
  {
    get { return search; }
    set {
        search = value;
        ResultList = GetNewList(search).Result.ToList(); 
      }
  }

引用 Data Binding文档:

In addition to handling onchange events with @bind syntax, a property or field can be bound using other events by specifying an @bind-value attribute with an event parameter (@bind-value:event).

关于c# - @onkeypress 没有获取文本输入框的更新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58343192/

相关文章:

c# - 在c#中从xml获取节点

c# - 如何确保使用 ASP.NET MVC5 和 IIS 7.5 express 刷新 CSS 文件

asp.net-mvc - RenderPartial 问题(将数据发送到母版页时)

asp.net-mvc - MVC Razor RadioButtonFor : How to have NO preset @checked?

asp.net-mvc - Razor 中的 Direct Model.Property 与 Html Helper DisplayFor

generics - Blazor 组件中的泛型类型参数可以受到约束吗?

c# - 如何将 C# 和 C++ 程序集链接到单个可执行文件中?

c# - 如何使用 Python for .NET 正确嵌入

html - CKEditor Blazor 集成

asp.net - 没有 Duende 身份服务器的 Blazor