将Javascript值传递到C#代码隐藏(扫描)中

Pass Javascript value into C# Code Behind (Scanning)

本文关键字:隐藏 扫描 代码 Javascript 值传      更新时间:2023-09-26

我有一个扫描仪,它在扫描条形码时会调用JavaScript函数。在这个函数中,我试图将条形码值传递到某种变量中,以便在C#代码后面使用。我试过这个:

document.getElementById("hidden").value = data;
alert(document.getElementById("hidden").value);

这会扫描条形码值并提醒它。在后面的代码中,我正在寻找这样的东西:

protected void hidden_ValueChanged(object sender, EventArgs e)
{
//magic wizard man stuff going on
}

这似乎根本没有触发。有什么想法吗?

(本质上,我希望一个值被传递到C#代码背后,这样我就可以用它做一些事情)

您最终必须进行回发,但如果您可以创建一个按钮并从javascript代码中单击它,那么这可能是一个更容易的解决方案。

将该事件附加到类似的隐藏字段

<asp:hiddenfield id="hidden"
              onvaluechanged="hidden_ValueChanged"
              value="" 
              runat="server"/>

MSDN源

为了实现这一点,您可以使用,Page Method。另一种选择是使用jquery,就像这样(只是一个代码片段):

$.ajax({
          type: "POST",
          url: "WebForm.aspx/CodeBehindMethod",
          data: "{<your scanner id>}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          async: true,
          cache: false,
success: function (msg) 
        {
                       //any div or label you want to update
                }
              })

在你的代码后面:

[WebMethod]
public static string CodeBehindMethod(string Id)
{
   //whatever you want to do with the Id
   return Id;
}