Hello Folks,
Today I will discuss about calling JavaScript function from ASP.NET code behind. The idea is sometimes we need to pass the server side data to the JavaScript methods. In this case we require to call the JavaScript from the code behind and pass the required parameter.
Here is the code that will register the script block on
the page and call the JavaScript message with the parameters passed from the code.
private void MethodRegisterJavaScript()
{
int a
= 5; int b = 6;
StringBuilder script
= new StringBuilder();
script.Append("<script type=\"text/javascript\">");
script.Append("DisplayMessage('" + a + "', '" + b + "'
)");
script.Append("</script>");
Page.ClientScript.RegisterClientScriptBlock(typeof(object), "JavaScriptBlock", script.ToString());
}
In the above method I am passing parameters a, b to JavaScript
function DisplayMessage.
Now as per the requirement we can call MethodRegisterJavaScript, which will register the Script on page and call the JavaScript Method.
Important point to note is that ClientScriptManager class has two
methods RegisterClientScriptBlock and RegisterStartupScrip both can be used to register
the required script on the page but there is little difference with respect to location
on page where they get registered.
RegisterStartupScript method registers the Script block at the bottom of page just before the closing form tag. Advantage of this method is that if one is using any of the control’s ID in the JavaScript method, it will work fine as script get introduced on the page after all the controls are loaded.
RegisterClientScriptBlock will
be registered on the page before any of the control loads. So use this method only
if you are sure that JavaScript method you are calling does not refer to any of
the control’s ID.
Happy Coding J
Related Posts:
Modify webconfig file
at runtime
How to Read XML Data
into DataSet
The path format is
not supported
C# Null-Coalescing
Operator (??)
Relative Path not
working after URL Rewrite
MIME TYPE: Fetch MIME
type from Registry
Convert Integer to
Enum instance