Javascript functions inside ASP.NET User Control
Solution 1
You need to register your scripts with ClientScriptManager
- this way they can be registered once, regardless of how often the control has been added to the page:
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
Solution 2
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);
}
Solution 3
You need to use this.id
$(document).ready(function () {
load_v<%= this.ID %>
});
function load_v<%= this.ID %>(fromclick) {
alert('anything');
}
So that even if you need two or more same controls in the same page they will have different ids. Hope this Helps! cheers :)
Anton
Sitecore Technology MVP 2019-2021. Co-founder of Sitecore Development Company: EXDST
Updated on July 09, 2022Comments
-
Anton almost 2 years
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.