ASP.NET OnTextChanged方法

时间:2015-08-21 10:48:45

标签: c# asp.net web

我有ASP.NET网站,有一个页面,当用户必须在文本框中输入文本时,图像应该出现取决于输入的文本。一切正常,但只有按Enter键才会显示图像,输入字母时是否有图像显示,而不是按Enter键?

<asp:TextBox ID="initials" runat="server" Width="50px" OnTextChanged="initials_TextChanged" AutoPostBack="true"></asp:TextBox> 

代码背后:

protected void initials_TextChanged(object sender, EventArgs e) 
{ 
    if(this.initials.Text == "A") { prvwleft.ImageUrl = "~/Images/left/A1.jpg"; } 
} 

2 个答案:

答案 0 :(得分:1)

在asp.net中,OnTextChanged事件会在您离开焦点时触发。

在您的情况下,您应该参加KeyDown活动。

Asp.net Textbox没有服务器端KeyDown事件,因此我们必须使用jquery来完成:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>

<script type="text/javascript" language="javascript">
    $(document).ready(function(){
        $('#initials').keypress(function () {
            if ($(this).val() == "A") {
                $('#prvwleft').ImageUrl = "~/Images/left/A1.jpg"; 
            }
            else {
                $('#prvwleft').ImageUrl = "~/Images/left/A1.jpg"; 
            }
        })
    });        
</script>

答案 1 :(得分:0)

你需要在这样的javascript中调用 onkeypress 事件

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function tSpeedValue(txt)
    {  

        alert("hi");
        var at = txt.value;
        alert(at);

    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" onkeypress="tSpeedValue(this)"></asp:TextBox>
    </div>
    </form>
</body>
</html>

如果你想在服务器端调用它

 <asp:TextBox ID="TextBox2" runat="server"   onkeypress="__doPostBack(this.name,'OnKeyPress');" ></asp:TextBox>

并在.cs页面中,代码应该像

protected void Page_Load(object sender, EventArgs e)
    {

        var ctrlName = Request.Params[Page.postEventSourceID];
        var args = Request.Params[Page.postEventArgumentID];

        if (ctrlName == TextBox2.UniqueID && args == "OnKeyPress")
        {
            TextBox2_OnKeyPress(ctrlName, args);
        }
    }



 private void TextBox2_OnKeyPress(string ctrlName, string args)
        {
            //your code goes here
        }
相关问题