0

In the below code i have a textbox .My aim is when focus comes in the textbox it has to call the server side method in codebehind using asp.net web application.Pls help me to do this. design code:

<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" OnTextChanged="txtField_TextChanged"></asp:TextBox>

code behind:

 void txtField_GotFocus(object sender, EventArgs e)
        {
//code
}
user3224577
  • 37
  • 1
  • 1
  • 9

1 Answers1

0

Assuming you don't want full page reload when focusing, make the method a Page Method then use AJAX to invoke it.

For this to work, first of all add reference to the assembly System.Web.Services in your project then change the code behind method to:

[System.Web.Services.WebMethod]
public static void txtField_GotFocus()
{
    //code here
}

Now to invoke it, my advice is to use jQuery which makes it really easy and simple. Having jQuery included, just have such code:

$(document).ready(function () {
    $("#<%=txtField.ClientID%>").bind("focus", function () {
        $.ajax({
            type: "POST",
            url: "<%=Request.FilePath%>/txtField_GotFocus",
            data: "{}",
            contentType: "application/json",
            dataType: "json",
            success: function (msg) {
                //alert("success message here if you want to debug");
            },
            error: function (xhr) {
                var rawHTML = xhr.responseText;
                var strBegin = "<" + "title>";
                var strEnd = "</" + "title>";
                var index1 = rawHTML.indexOf(strBegin);
                var index2 = rawHTML.indexOf(strEnd);
                if (index2 > index1) {
                    var msg = rawHTML.substr(index1 + strBegin.length, index2 - (index1 + strEnd.length - 1));
                    alert("error: " + msg);
                } else {
                    alert("General error, check connection");
                }
            }
        });
    });
});

And your code behind method will be executed when textbox is focused.

Note that being static, you need to change how you access Request and Response objects (and the likes) for example to access Request, have:

[System.Web.Services.WebMethod]
public static void txtField_GotFocus()
{
    string foo = HttpContext.Current.Request["foo"];
    //code...
}
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208