[英]Get value of an input field in Blazor without @oninput
I have an HTML <input>
element that is generated by a Blazor <InputText>
component.我有一个由 Blazor
<InputText>
组件生成的 HTML <input>
元素。
I am using a JavaScript library to detect when the user scans a barcode.我正在使用 JavaScript 库来检测用户何时扫描条形码。 When this event occurs I set the value of the scanned barcode into the
<input>
element.当此事件发生时,我将扫描条形码的值设置到
<input>
元素中。
I want to be aware of this change of value immediately in C#.我想立即在 C# 中了解这种价值变化。 Normally I'd use
@bind-event:oninput
to ensure I have the current value immediately whenever it changes, but this event isn't fired when the HTML input's value is set via code.通常我会使用
@bind-event:oninput
来确保在它发生变化时立即获得当前值,但是当通过代码设置 HTML 输入的值时,不会触发此事件。
Is there a way to assign a value to an HTML input via JavaScript and then have C# immediately aware of the change and update the property of the C# object the InputText
control is bound to? Is there a way to assign a value to an HTML input via JavaScript and then have C# immediately aware of the change and update the property of the C# object the
InputText
control is bound to?
I have solved this the following way:我已经通过以下方式解决了这个问题:
Where you have the value in JS that you want in C#, apply it to a field and call.click() on a button.如果您在 C# 中具有所需的 JS 值,请将其应用于字段并在按钮上调用.click()。 This button calls a C# method that invokes a JS function that returns the value of the input as a string to your C# method, which you can now use however you want.
此按钮调用 C# 方法,该方法调用 JS function 将输入值作为字符串返回给您的 C# 方法,您现在可以随意使用该方法。
While it is a dirty solution, it worked.虽然这是一个肮脏的解决方案,但它确实有效。
I have tried to get invokeMethodAsync to call my C# method directly, but that required it to be static and I simply didn't have the time for this project to do it the proper way.我试图让 invokeMethodAsync 直接调用我的 C# 方法,但这需要它是 static 而我根本没有时间让这个项目以正确的方式完成它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.