PDA

View Full Version : ASP. NET client side scripting advice


alex57
04-01-2010, 10:18 AM
Hello,

I used to work in PHP and sometimes used form elements like below to call javascriot functions.

<a href=”javascript: void(0);” onClick=”DoSomething();”>Hyperlink</a>

However, I have turned to ASP .NET and these are server side controls and the onClick event fires server side coding. How would you call client side scripting (ie. Javascript or equivalent) from a server side control? Can you harness the power of C# (ie full OO programming) on the client side?

Any advise on client side scripting using C# will be welcome.

Mike_O
04-01-2010, 03:44 PM
Hey alex57,

Some server side controls (since the .NET 2.0 framework I think) now include a few client-side event handlers. For example:
<asp:Button ID="Button1" runat="server" OnClientClick="abc()" />

This will call JavaScript function abc() when button is clicked. These certain client-side handlers for server-side controls is unfortunately very limited in its number. I haven't worked with the latest .NET framework (3.5 is it now? I don't keep track) Anyway, you can add any client-side handler to a server-side control programmatically in the code-behind. Let's say we want to add a mouseover event to the above button example. It would be something like this inside your Page_Load(...) or whatever: Button1.Attributes.Add("onmouseover","def()");

Lastly, I should mention that you can also have the regular html tags, and if you put attribute "runat='server'" inside them, you can now reference them and control their attributes within the code-behind. I am not sure if you can do that with all the tags, or if you're able to control all its attributes, so don't kill the messenger. Here's a small example. On the aspx page, you can have this: <input type="button" id="button2" runat="server" /> And then in the code-behind, you can have this: button2.Value = "click me";

Regards,
Mike

alex57
04-02-2010, 03:39 PM
thank you. Very clear and I will look into this further.