Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript function from c#

I like to call a JavaScript function from c#. Can any one can give me code snippet.

More detail...

I have a asp.net page which has a asp button. when i click that button, i like to call javascript function.

like wise....

in my asp.net page,

<button id="save" onclick="i like to call a method resides in asp.net page'>Save</button>

More and more details... when click the asp.net button, i like to perform some server side action and then like to call a javascript function from there itself...

like image 269
Partha Avatar asked Apr 22 '10 18:04

Partha


2 Answers

For an asp:button you use OnClientClick

<asp:Button id="myid" runat="server" OnClientClick="alert('test')" />
like image 187
Mikael Svenson Avatar answered Oct 06 '22 00:10

Mikael Svenson


On the assumption that you're coding in ASP.NET (including MVC), calling a JavaScript function would mean embedding the call in JavaScript into your ASPX code, like so:

<script type="text/javascript">
  doSomething();
</script>

You do have the opportunity to pass information from your C# to the JS call, just as you would have any other code alter the results of your ASPX:

<script type="text/javascript">
  doSomething("<%= GetSomeTextFromCSharp();  %>");
</script>

This is really stretching the definition of "calling JavaScript from C#" though. What you're doing is having your C#/ASPX code generate HTML/JavaScript, which the browser then interprets as it would any other HTML/JS (regardless of how it was generated).

Perhaps you could explain what you're trying to do a bit more.

like image 24
Craig Walker Avatar answered Oct 06 '22 01:10

Craig Walker