Monday, August 12, 2013

ASP.NET Call CodeBehind function from JavaScript

A small tips about how to ASP.NET Call Code Behind function from JavaScript:

Lets have a simple scenario

We have a ASP Text Box and onblur  we will call java script and then from java script we will again call Code Behind Method:

Suppose we have added Text Box tb_1 and in Page load added below Code:


protected void Page_Load(object sender, EventArgs e)
{       
        tb_1.Attributes.Add("onblur", "greet()");        
}

So on Blur below java script will call:

<script type="text/javascript">
   function greet() {
            var name = document.getElementById("tb_1").value;
            alert(name);
            var s= '<%=fromJS() %>';
            alert(s+name);
   }
</script>

And Now:
We have added fromJS() method in Code Behind:

[System.Web.Services.WebMethod]     //required to know that this is web method
public string fromJS()
{
    string s = "welcome " + tb_1.Text;
    return s;
}

References:
1. http://social.msdn.microsoft.com/Forums/vstudio/en-US/c1936c94-9719-4fdb-8204-03b73b7c1241/call-code-behind-function-from-java-script-function
2. http://www.codeproject.com/Articles/180355/Calling-a-code-behind-function-from-JavaScript

No comments:

Post a Comment

http://myaspdotnetworld.blogspot.com