Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript functions inside ASP.NET User Control

I created ASP.NET user control with javascript function :

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="BingTranslator.Web.WebUserControl1" %>
<script type="text/javascript">
    function example() {
        alert('<%=ExampleButton.ClientID%>');
        return false;
    }
</script>
<asp:Button ID="ExampleButton" runat="server" Text="Example"/>

I want to call "example" function when user move mouse to button, so I added attribute for button:

ExampleButton.Attributes.Add("onmouseover", "example()");

It works well, but when I need two controls on same page I got a problems. ASP.NET generates code with two functions with same name, what is wrong:

<script type="text/javascript">
    function example() {
        alert('TestControl1_ExampleButton');
        return false;
    }
</script>
<input type="submit" name="TestControl1$ExampleButton" value="Example" id="TestControl1_ExampleButton" onmouseover="example()" />


<script type="text/javascript">
    function example() {
        alert('TestControl2_ExampleButton');
        return false;
    }
</script>
<input type="submit" name="TestControl2$ExampleButton" value="Example" id="TestControl2_ExampleButton" onmouseover="example()" />

And always onmouseover event on any button will call second function. I am able resolve this issue by adding java script code with client Id directly to attriburte onmouseover.

ExampleButton.Attributes.Add("onmouseover", "[Here will be javascript code]");

But it is not very harmonious solution as for me. Please advise, how I can better resolve such issue.

P.S. There will be much more Javascript code, I added two string upper just for example.

like image 808
Anton Avatar asked Dec 11 '10 12:12

Anton


1 Answers

I found a solution in another site which allows you to use external file

if (!Page.ClientScript.IsClientScriptIncludeRegistered("key"))

{

   string url = ResolveClientUrl("~/Scripts/file.js");

   Page.ClientScript.RegisterClientScriptInclude("key", url);

}
like image 130
Ronen Festinger Avatar answered Sep 21 '22 12:09

Ronen Festinger