Including Javascript with a custom control in an ASP.Net website - asp.net

I have a custom date control which is essentially a text box and the ajaxToolKit calendarExtender. I want to include Javascript in the control and have it work properly no matter what page the control is on. The control is called DateControl.ascx
So I have two Javascript functions, dateEditor_OnShown and dateEditor_OnHiding. They get tied up in the page load of DateControl.ascx via...
CalendarExtender.OnClientShown = "dateEditor_OnShown";
CalendarExtender.OnClientHiding = "dateEditor_OnHiding";
The DateControl tool is used on two separate pages. If I put the straight Javascript directly into the DateControl's HTML it will work only on the default page but crashes when I load up the next page with the control. The error is a js runtime error 'dateEditor_OnHiding' is undefined.
If I try to link to the Javascript file from my DateControl's html via...
<script type="text/javascript" src="../JavaScript/IE6CalendarExtenderFix.js"></script>
... instead of having the Javascript directly in the page, it crashes immediately with the same error. I should note that the path to the js is correct.
The only way I can really get it to work is if I link to the javascript on every page that the control is used.
UPDATE: I feel the need to clarify a little bit. The solutions suggested are much appreciated, but either I am not understanding or they just will not work in my case for whatever reason (quite possibly the former).
So, this is basically what my control looks like...
<div id="CustomDateControl" style="<%# ControlStyle %>">
<div id="TextBox" style="display:inline; white-space:nowrap;">
<asp:TextBox runat="server" ID="txtCalender" Style="<%# TextBoxStyle %>" />
</div>
<div id="Calendar" runat="server">
<ajaxToolkit:CalendarExtender
runat="server"
ID="CalendarExtender"
Format="MM/dd/yyyy"
TargetControlID="txtCalender"
PopupButtonID="CalenderImage" />
</div>
</div>
In the aspx page, with that exact code, if I put the exact javascript in script tags so the page looks about like so...
<script type="text/javascript">
function dateEditor_OnShown(dateControl, emptyEventArgs) {
...
}
function dateEditor_OnHiding(dateControl, emptyEventArgs) {
...
}
</script>
<div id="CustomDateControl" style="<%# ControlStyle %>">
<div id="TextBox" style="display:inline; white-space:nowrap;">
<asp:TextBox runat="server" ID="txtCalender" Style="<%# TextBoxStyle %>" />
</div>
<div id="Calendar" runat="server">
<ajaxToolkit:CalendarExtender
runat="server"
ID="CalendarExtender"
Format="MM/dd/yyyy"
TargetControlID="txtCalender"
PopupButtonID="CalenderImage" />
</div>
</div>
This still crashes when accessing the control in the second page (not the first which is the default page) saying 'dateEditor_OnHiding' is undefined. Now, if I link to a js file with the same code using a relative path as suggested below I still get the same results.
Also, if as suggested below, I override OnPreRender and run RegisterClientScriptInclude, I once again get the same results. The control always works on the default page but never on the second page even though as far as I can tell the script is included in the control.
Any ideas?

append following code in your User Control.
protected override void OnPreRender(EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("DateControl", this.ResolveClientUrl("~/JavaScript/IE6CalendarExtenderFix.js"));
base.OnPreRender(e);
}

Problem with control-relative file paths
You are probably having problems with relative paths to your JS file. You are specifying relative path to your custom control. You should probably write user control. Anyway. Your JS file is relative path to your custom control, but not relative to the containing page, so your JS file actually never loads. That's why your event handlers are undefined.
The easiest way would be to use absolute paths. Since you're working with user controls you can easily prepend application root folder.

Related

Javascript won't work on Html server control?

I am writing a website with ASP.Net.
I will have lots of html generic controls like <div> <span> and so on..
I have some onclick javascript functions, onmouseover javascript functions..
They are working fine..
Then I need to control them on the server side.
So, I add runat="server"..
After that, all the javascripts aren't working anymore..
I understand they aren't working coz all the events are now going back to server side.
So, is there anyway to make them work??
For eg,
<div id="myDiv1" onclick="myfunction(para1)"><img src="..." /></div>
the above code is working..
<div id="myDiv1" runat="server" onclick="myfunction(para1)"><img src="..." /></div>
the above code is not working...
I can make it work, probably by
<div id="externalDiv1" onclick="myfunction(para1)"><div id="myDiv1" runat="server" ><img src="..." /></div></div>
Is there any other way?
I assume that you used document.getElementById() to get an element by its id. If you are using master pages, the IDs of server controls will be changed after rendering to the page, in that case, you have to use its ClientID
for e.g.
var myDiv1 = document.getElementById("<%= myDiv1.ClientID %>");
Server-side or client-side controls makes no difference as far as javascript is concerned. ALL server-side controls end up being rendered as normal HTML controls. If your javascript functions are not working might be because you are accessing them by the wrong id since by making them server-side controls they can now have ids that follow a pattern like <parent_id>_<control_id>.
For example, a span element declared like this:
<span id="mylabel" runat="server"> testing</span>
may end up being rendered as:
<span id="MainContent_mylabel"> testing</span>
ASP.NET 4.0 has a feature called CliendIDMode which can be set to static, meaning, that your ids on the markup will stay unchanged after the page is rendered.

Access to events?

i have a question about generating images at runtime which are also links. Ok, so what i was going to do was create an ImageButton, and then set the onClick event to something such as:
window.open('http://www.themagicfinger.com/')
Which means it would look like:
newImage.Click += (window.open('http://www.themagicfinger.com/'));
But then i realised that this doesnt work, because it looks for a method which matches the event delagate.
So my question is, is this the best way to achieve what i want, and if so, how can i make it work?
Another option that came in my head would be to wrap the image in an tag, but i think this way its better.
Thanks
What you need is OnClientClick:
<asp:ImageButton id="ImageButton1" runat="server" OnClientClick="window.open('http://www.themagicfinger.com/'); return false;" ImageUrl="MyButton.png" />
This property is a string, not event, and you can also assign it from within the code behind:
ImageButton1.OnClientClick = "window.open('http://www.themagicfinger.com/'); return false;";
If you're asking how to use server-side code to tell the client to open a browser window, you can't. The server-side code has no means of telling the client to do that. The only thing you'd be able to do from server-side code is emit client-side that does this. And in that case, why use the server-side code at all?
Using jQuery for example, you can attach the click event like this:
<!-- page header (including loading jQuery), other stuff that's before the image, etc. -->
<img src="/path/to/image" alt="some text" id="imgOpenWindow" />
<!-- the rest of the page -->
<script type="text/javascript">
$(document).ready(function() {
$('#imgOpenWindow').click(function(){
window.open('http://www.themagicfinger.com/');
});
});
</script>
If for some reason you need to use an ImageButton control for this then it would look like this:
<!-- page header (including loading jQuery), other stuff that's before the image, etc. -->
<asp:ImageButton run="server" id="imgOpenWindow" ImageUrl="/path/to/image" AlternateText="some text" />
<!-- the rest of the page -->
<script type="text/javascript">
$(document).ready(function() {
$('#<%= imgOpenWindow.ClientID %>').click(function(){
window.open('http://www.themagicfinger.com/');
});
});
</script>
But I'm not sure what the behavior would be with the post-back. It might override the JavaScript handler (by posting back before your handler is executed) or post-back after the window opens, etc. I would consider that behavior to be undefined and unreliable. An Image control will do the trick, though, if you don't need the button post-back capabilities.

ASP.Net: Get page url from inside a frame

How can I get the top page URL from inside a frame?
(in javascript it's implemented using : window.top.location)
You can't.
The fact that the page is going to be loaded into an iframe in another page is not sent in the request to the server, so it's not possible to get the ULR of the parent page, or even to determine if there is a parent page or not.
If you need that information on the server side, you have to add that information to the request, for example by including the parent page URL as a querystring parameter.
In case people need it, there's a way for this certain purpose. At least I solved somehow.
First, place a button running at server, add a click event and a client-click event.
<asp:Button ID="btnFindParentUrl" runat="server" Text="Get Url!" OnClick="btnFindParentUrl_Click" OnClientClick="fillHidden();" />
Put a hidden textbox inside a div with style="display: none;" (not Visible="false" for button because if you do client can't see and fill it):
<div style="display: none;">
<asp:TextBox ID="txtHiddenUrlField" runat="server" BorderStyle="None" Font-Size="0px" ForeColor="#F6F6F6" Height="0px" Width="0px"></asp:TextBox>
</div>
Now place javascript code of fillHidden() function:
<script type="text/javascript">
function fillHidden() {
document.getElementById('<%= txtHiddenUrlField.ClientID %>').value = parent.document.location.href;
};
</script>
That's all you have to do at client side.
Let's go to the server:
protected void btnFindParentUrl_Click(object sender, EventArgs e)
{
string parentUrl = txtHiddenUrlField.Text;
}
This way, you should be getting parent url from button in an iframe.
Anyone needs help may ask question here or to this code's post in my personal site.
you can do this if the frame + parent are both on the same domain. if so, then you can obtain references to other iframes, frames or pop-ups.
from memory, try window.parent, so yours would be something like window.parent.top.location

Can I use update panels with jQTouch?

I am using ASP.NET controls to fill in HTML for my jQTouch application, but I am having trouble with my hrefs ceasing to function as intended on my search page. The jQuery function for my anchor class evidently does not get called; it simply links back to the default page, even though the link is built similarly on other pages without any problems.
This is where my links are breaking:
<form id ="form1" runat="server" class="form">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" ID="up1">
<ContentTemplate>
<ul class="rounded">
<li><asp:TextBox ID="txtSearchString" runat="server" name="search-articles" placeholder="Search GROK"></asp:TextBox></li>
<li><asp:Button ID="btnSearch" runat="server" Text="Search" type="rounded" OnClick="btnSearch_Click"></asp:Button></li>
</ul>
<asp:Literal ID="litSearchResults" runat="server"></asp:Literal> <%--HTML for jQTouch inserted here--%>
</ContentTemplate>
</asp:UpdatePanel>
</form>
This is an example of the HTML generated by code behind.
<ul class="edgetoedge"><li class="sep">Found 101 articles</li><li>PAWS: How to Access the Sample Test Database</li><li>Mac OS X: Hardware Test</li><li>The JavaScript Test</li><li>PAWS: Emergency Text Message Test</li><li>Definition: remote digital loopback test</li><li>Definition: power-on self test</li><li>Definition: power-on self test</li><li>AVG 9.0 Free Edition: Setting Scan Process Priority</li><li>Microsoft Office 2007: Diagnostics</li><li>Moodle: Description of Aggregation Methods</li><li>AVG 9.0 Free Edition: How can I run the complete scan of whole computer?</li><li>LSU A-Z: Office of Assessment and Evaluation</li><li>Linux: sed Insert a Newline Into the RHS of a Substitution</li><li>Microsoft PowerPoint 2007: Narrating a Slide</li><li>Ubuntu: Deleting Undeletable Files In the Trash</li><li>Linux: Remove All Digits/ Input From Inputs</li><li>SQL: Create a MySQL DocDB Databse</li><li>Linux Gnome: Screens and Graphics</li><li>Linux Xfce: Adjust keyboard settings</li></ul>
jQTouch handles every other tag normally, it is just the anchors that have ceased to function as intended by being placed inside this form. Can I keep using update panels here or will it inevitably break? Is there a work-around? Or am I approaching the problem incorrectly?
Keep in mind I want to retain the AJAXical animations produced by jQTouch. If you find that I am unclear or you would like to see more code (I only included what I believe to be necessary), please let me know.
Bonus points if you can tell me how to get jQTouch to replace the ugly the ASP.NET button control with an iPhoney button. :)
I think you are going to have to do a ton of hacks to get ASP.Net working with jqtouch with update panels, as you are going to be fighting the JavaScript inserted by ASP.Net with the JavaScript that jqtouch inserts. In your example all your links are going to the same anchor (#article). To do this in a jQtouch kind of way, you would have all the the links going to '#' and handle the tap of the articleLinkClass and then adjust as you need to.
$('.articleLink').tap(function()
{
var id = $(this).val('id');
// Pseudo CODE HERE FOR Setting up the article based on id... E.g.
$.json(jsonServiceUrl, { article_id: id }, function(data)
{
$('#article data).html(data);
});
jQt.goTo('article'); // Display the article page...
});
The iPhoney buttons are created in jQtouch as 's with their class as "whiteButton", i.e.:
<a id="myTestButton" class="whiteButton">Test Button</a>
Hope this helps...

Expanding ClientID in an event string

I'm having a problem with <%= obj.ClientID %> expansion, in a .ascx user control.
I have a .js file, containing a javascript function:
function doSomething(objectId)
{
...
}
I have a .ascx file, with some html elements, and in one element's onclick= I want to call doSomething(), passing the ID of an element in that .ascx file, where the passed ID is of an element other than the one being clicked on, so I can't use "this.".
Maybe it'd be clearer with an example.
This works:
<script type="text/javascript">
function redirect()
{
doSomething('<%= top.ClientID %>');
}
</script>
<div id="top" runat="server">
<img src="..." alt="..." onclick="redirect();"/>
</div>
But this does not:
<div id="top" runat="server">
<img src="..." alt="..." onclick="doSomething('<%= top.ClientID %>');"/>
</div>
When I look at the source, I see that the <%= %> substitution has not happened, instead of "doSomething('ctl00_myControl_top');" I get "doSomething('<%= top.ClientID %>');"
For some reason, the script expansion happens in the former case, but not in the latter. The work-around, of course, is not acceptable because it will break if I include multiple copies of the control on a page - only one instance's "redirect()" function will be accessible.
Any ideas on how to make this substitution work?
Works on my machine?
<div id="top" runat="server">
rarrarara
</div>
Becomes
<div id="ctl00_ContentPlaceHolder1_top">
rarrarara
</div>
Consider an alternate route:
Ensure that the control you are referencing in JavaScript using the inline expression <%= (controlName).ClientID %> has its 'ClientIDMode' specifier set to a static value and then simply use the text in the ID field of that control to refer to it. I ended up using this in a recent project it works great. Please see the link below for a more detailed explanation:
Code Project - ASP.NET v4.0 Client ID Feature
Along with setting the 'ClientIDMode' specifier to "Static", I found a useful idea regarding placing text from a global resource file (in the case of language switching) into a field of a standard HTML control that does not have to run at the server level. I used this on a standard HTML button that was supposed to call a JavaScript function that would show/hide a specific div or ASP Panel. Use the GlobalResource function in the inline expression tags like so:
<input id="btnToggleFilterOptions" type="button" value="<%=GetGlobalResourceObject("SiteResource", "btnToggleFilterOption")%>" onclick="javascript:ToggleCssClass('divFilterOption','visible'); return false;" class="button submit" />
<asp:Panel ID="divFilterOption" ClientIDMode="Static" runat="server">
<asp:TextBox ID="txtFilterOption1" runat="server" />
</asp:Panel>
I know this is an old post, but it is a popular hit when searching on Google for Asp .NET and ClientID. I hope this helps somebody else out!

Resources