How to call javascript function from code behind?

I want to execute javascript function from code behind page.

I have two way that first that I can call javascript of html page in my code behind.

second is that i can write javascript function in to my code behind.

but i am not which one is better and how can i do this.

Please tell me that how can i do this.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

ScriptManager.RegisterStartupScript(...)

Look here for details

Method 2

You can call Js functions as a script registered on the codebehind itself.

Page.RegisterStartupScript("key","value")

key is the name you want to give the script eg. “PageClose”
value is the;

stringBuilder str = new StringBuilder()
str.Append("<script = language='javascript'>");
str.Append("window.close();");
str.Append("</script>")

here instead of using the window.close you coud append your js function as a string, ideally i put this string builder class and build the script in the constructor if i need it always in the page

Then use this in the event handler you want to execute the script

Page.RegisterStartUp("PageClose",str.ToString());

This would place the javascript before the closing tag of the page thats rendered

Page.ClientScriptBlock("PageClose",str.ToString());

This would place the JS function after the opening tag of the page thats rendered

Hope this helps

Method 3

Try the following in your codebehind

ClientScript.RegisterStartupScript(GetType(), "scrptName", "javascript: alert('hi'); ", true);

You can replace alert(‘hi’); with your javascript function you want to call from code behind.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x