从html输入文本类型的文本框中获取字符串形式的值,并将其传递给aspx中正在使用的C#哈希表

本文关键字:aspx 哈希表 文本 输入文本类型 html 获取 字符串 | 更新日期: 2023-09-27 18:26:08

文本框被定义为html输入文本类型,并接受用户的输入。需要将此值作为关键字传递到aspx文件中使用的aspx.cs文件中定义的哈希表。但是没有给出正确的值,并且抛出了一个异常。在这方面的任何帮助都是有益的。感谢

代码如下:

    <% =Hashtable[document.getElementbyId("Textbox").Value]%>

document.getElementbyId("Textbox").Value没有给出正确的输出。如果它被一个充当键的字符串值所取代,那么它就可以正常工作。唯一的问题是从文本框中获取字符串值。

从html输入文本类型的文本框中获取字符串形式的值,并将其传递给aspx中正在使用的C#哈希表

首先在头段中包含jquery

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

尝试以下代码读取文本框值:使用首次读取文本框值

var key = $("[id$=Textbox]").val();

并查看texbox中是否存在值(如果存在)使用该值读取哈希值

 <% =Hashtable[key]%>

试试这个,它对我有用:aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
       <script>
           function GetHashtable() {
               alert("<% = hashtable[this.test] %>");
            }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtKey" OnTextChanged="txtKey_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
        </div>
    </form>
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>

代码背后:

public partial class _Default : System.Web.UI.Page
{
    protected int test;
    public Hashtable hashtable = new Hashtable();
    static Hashtable sHashtable = new Hashtable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            sHashtable[1] = "One";
            sHashtable[2] = "Two";
            sHashtable[13] = "Thirteen";
        }
    }
    protected void txtKey_TextChanged(object sender, EventArgs e)
    {
        test = Convert.ToInt32("0" + txtKey.Text);
        hashtable = sHashtable;
        Page.ClientScript.RegisterStartupScript(this.GetType(), "GetHashtable", "GetHashtable();", true);
    }
}