1

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.

1
  • I really cannot understand what is your issue! Commented Feb 23, 2013 at 2:56

3 Answers 3

7
ScriptManager.RegisterStartupScript(...)

Look here for details

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I had enabled partial rendering and not using ScriptManager caused everything to stop working. Nearly drove me crazy.
1

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

2 Comments

StringBuilder str = new StringBuilder(); str.Append("<script = language='javascript'>"); str.Append("{"); str.Append(" chooseStyle(" + colr + "," + wd + "); "); str.Append("function changeCSS()"); str.Append("}"); str.Append("</script>"); Page.RegisterStartupScript("PageClose", str.ToString()); I am using this. But its not working
I want to set the value colr and wd in chooseStyle on page load. but right now its not working
1

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.

3 Comments

what is the meaning of GetType() and scrptName
RegisterStartupScript (type, key, script) here GetType() returns type of the page. And scrptName is the key.
msdn.microsoft.com/en-us/library/… check this link for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.