簡體   English   中英

從html輸入文本類型文本框中獲取值作為字符串,並將其傳遞給在aspx中使用的C#哈希表

[英]Get value from html input text type textbox as string and pass it to C# hashtable being used in aspx

文本框定義為html輸入文本類型,並接受用戶的輸入。 需要此值作為鍵傳遞給在aspx文件中使用的aspx.cs文件中定義的哈希表。 但是沒有給出正確的值,並且拋出了異常。 在這方面的任何幫助將是有幫助的。 謝謝

代碼如下:

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

document.getElementbyId(“ Textbox”)。Value沒有提供正確的輸出。 如果將其替換為用作鍵的字符串值,則它可以正常工作。 唯一的問題是從文本框中獲取字符串值。

首先在頭部添加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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM