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

and I have c# codebehind method:

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

But This code tries to execute JavaScript Function. How to execute c# function from code behind? I tried something like:

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

but didn't work.

user2114177
  • 273
  • 1
  • 9
  • 18
  • I think you need to learn about the difference between client-side and server-side coding. You're asking the browser to call a function on your server, which isn't going to work without a technology such as AJAX. – freefaller Aug 06 '13 at 10:25

3 Answers3

1

add below namespace

using System.Web.Services;

and define method like below

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

and call it from 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
            }
Nirmal
  • 924
  • 4
  • 9
1

try this

on textfocus call javascript function call_textbox2_focus() in this function click button

<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>

in code behind

    public void textbox2_focus(object sender, EventArgs e) { 

        var x = 5; 

    }
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
0

The onfocus event is a client-side event so you won't be able to directly access the server-side code.

You could run it through JavaScript and use an XmlHttpRequest or something similar to access a WebMethod written in C#.

Have a look at this answer: Calling a webmethod with jquery in asp.net webforms

Community
  • 1
  • 1
Sean Airey
  • 6,352
  • 1
  • 20
  • 38