0
<asp:TextBox runat="server" ID="textbox2" MaxLength="2" onfocus="textbox2_focus" />

我有 c# 代码隐藏方法:

public void textbox2_focus(object sender, EventArgs e) { var x = 5; }

但是这段代码试图执行 JavaScript 函数。如何从后面的代码执行 c# 函数?我试过类似的东西:

<asp:TextBox runat="server" ID="textbox2" MaxLength="2" onfocus="<%=textbox2_focus() %>"/>

但没有用。

4

3 回答 3

1

尝试这个

在 textfocus 上调用 javascript 函数call_textbox2_focus()在这个函数中单击按钮

<asp:TextBox runat="server" ID="textbox2" MaxLength="2" onfocus="call_textbox2_focus()" />
<asp:Button ID="btnCallCodeBehind" Text="text" runat="server" style="display:none;" OnClick="textbox2_focus"/>
<script type="text/javascript">
    function call_textbox2_focus() {
        document.getElementById('<%= btnCallCodeBehind.ClientID %>').click();
    }
</script>

在后面的代码中

    public void textbox2_focus(object sender, EventArgs e) { 

        var x = 5; 

    }
于 2013-08-06T11:00:46.470 回答
1

添加下面的命名空间

using System.Web.Services;

并定义如下方法

[WebMethod]
public void textbox2_focus(object sender, EventArgs e) 
{ 
var x = 5; 
}

并从ajax调用它

function textbox2_focus() {
       $.ajax({
               type: "POST",
               url: "pagename.aspx/textbox2_focus",
               data: '',
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: OnSuccess,
               failure: function (response) {
                // your code        
               }
             });
            }
    function OnSuccess(response) {

                  // your code
            }
于 2013-08-06T10:31:18.183 回答
0

onfocus事件是客户端事件,因此您将无法直接访问服务器端代码。

您可以通过 JavaScript 运行它并使用一个XmlHttpRequest或类似的东西来访问用 C# 编写的 WebMethod。

看看这个答案:Calling a webmethod with jquery in asp.net webforms

于 2013-08-06T10:28:02.737 回答