Accessing external javascript code in ASP.Net - javascript

I have a script block in my ASP.Net file, where I should access javascript of an external control. This doesn't seem to work at all, I tried all the solutions I found on the web, but probably I'm not searching for the right stuff. As far as I've seen the src attribute in the script tag would do the work, but I can't have own code and this src attribute it seems.
Interesting enough, it works proper when I just call the javascript function from the event. Something like this:
Works:
<stgwc:ImageLinkButton runat="server" ID="ImageLinkButton1" ImageUrl="~/Images/base/Icons/16x16/brush1.png" OnClientClick="GridRowEnterEditMode(this, 'EditRole'); return false;" />
And my approach was:
<stgwc:ImageLinkButton runat="server" ID="btnEditRole" ImageUrl="~/Images/base/Icons/16x16/brush1.png" OnClientClick="EnterRolesEditMode(this.id); return false;" />
function EnterRolesEditMode(btnClientId) {
var grd = document.getElementById('dgrRoles');
var btn = document.getElementById(btnClientId);
grd.GridRowEnterEditMode(btn, 'EditRole');
}

Related

execute javascript after download a file (RegisterStartupScript)

I want to execute a RegisterStartupScript calling a Javascript function after certain processes happen in my code behind. It is basically a Loading loop decoration made in CSS3. I show it (with javascript) on buttons clientclick, when I know the process will take a while and I hide it when the process is finished. Everything works fine, but now I have a process in Which I download a file using another empty webform using response.redirect. The file is downloaded fine, but the RegisterStartupScript call does not work. I understand the response is the problem, but nor I need to work in a workaround to solve this (I do not want to change the whole way, cause it is implemented in many other pages and processes. I wil provide the related code (not all), in case you can give me a direct way to solve it.
Javascript
function LoadingLoopOn()
{
$('#outerAlignId').addClass("outerAlign");
$('#middleAlignId').addClass("middleAlign");
$('#innerAlignId').addClass("innerAlign");
$('#OutterCircleId').addClass("OutterCircle");
$('#InnerCircleId').addClass("InnerCircle");
$('#Loadinglbl').addClass("LoadingLabelStyle");
}
function LoadingLoopOff()
{
$('#outerAlignId').removeClass("outerAlign");
$('#middleAlignId').removeClass("middleAlign");
$('#innerAlignId').removeClass("innerAlign");
$('#OutterCircleId').removeClass("OutterCircle");
$('#InnerCircleId').removeClass("InnerCircle");
$('#Loadinglbl').removeClass("LoadingLabelStyle");
}
HTML (it is on the master page, to be able to used it in every webform)
<asp:Panel ID="outerAlignId" ClientIDMode="Static" runat="server" CssClass="outerAlign">
<div id="middleAlignId" class="middleAlign">
<div id="innerAlignId" class="innerAlign">
<div id="OutterCircleId" class="OutterCircle"></div>
<div id="InnerCircleId" class="InnerCircle"></div>
<asp:Label ID="Loadinglbl" ClientIDMode="Static" runat="server" Text="Loading..." CssClass="LoadingLabelStyle"></asp:Label>
</div>
</div>
</asp:Panel>
HTML Button Sample Where I want to used it
<asp:ImageButton ID="ExportExId" ClientIDMode="Static" runat="server" OnClientClick="LoadingLoopOn();" OnClick="ExportExId_Click" CssClass="..." ImageUrl="..." />
And the CS# Code behind
protected void ExportExId_Click(object sender, ImageClickEventArgs e)
{
//...
//Many code and DB treatment goes here, to finally get a temporally Excel file in the server
//..
//I call the page with the file name and path
Response.Redirect(String.Format("DownloadForm.aspx?FileName={0}&Path={1}", fileExported.Name, "Temp" + UserName));
//This piece of code must be excuted in its webform after the redirect (once ee finished)
ScriptManager.RegisterStartupScript(this, GetType(), "LoadingLoopOff", "LoadingLoopOff();", true);
}
As I marked in my comment, A possible solution could be AJAX. Make an ajax call to force a page update and then the function would be processed (on the load), or directly call the function through this ajax call. The problem is that I do not know how to uise AJAX in this case...
Many thanks,

Control is not declared. It may be inaccessible due to its protection level

I'm really stuck and I've tried all the other examples but nothing works. I'm fairly new to ASP.NET but learning fast!
I want to use the jQuery datepicker and I am inserting this script
<script>
$(document).ready(function () {
$(function () {
$("#" + '<%=txtDOB.ClientID%>').datepicker();
});
});
</script>
and my control on the aspx page is
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server"></asp:TextBox>
As soon as I close the the server tag %> the red line appears under the txtDOB control and says:
txtDOB is not declared. It may be inaccessible due to its protection level.
I've made the class public in the code behind but doesn't make any difference. I've also moved the script to the bottom of the page. If I change the asp textbox to a HTML input it works fine.
It will work fine with an ASP.NET TextBox as you have used. Therefore it must be to do with where your control is located. For example, if it's inside a Repeater or Grid, you will not be able to use its ID directly like that, since the framework will generate unique ids for each row at runtime.
Create a simple webform with no other controls on the page, and you will find it works just as you have it.
Try using static ID mode instead:
<script>
$(document).ready(function () {
$("#txtDOB").datepicker();
});
</script>
It makes the client script easier (especially when you move it to an external .js file to take advantage of caching), and is an easy change to the ASP control:
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server" ClientIDMode="Static"/>
You could use a different type of jQuery selector to select for that ID as follows:
<script>
$(document).ready(function () {
$("input[id$=_txtDOB]").datepicker();
});
</script>
That selector will account for the text that is being appended to the beginning of your ID due to the use of your CreateUserWizard control. It is cleaner than the way you are currently doing it, and you can use your original HTML.
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server"></asp:TextBox>

Controls in ContentPlaceHolder are not recognized by javascript document.getelementsbyname

I have a calender script in my project. For using it, I have added an image and on its onclick event I call a javascript function displayDatePicker:
<img alt="Calender" src="calender.jpg" onclick="displayDatePicker('txtBox1', this);"/>
I use a masterpage in my project and if the image and the associated textbox control are in contentPlaceHolder, the javasript library's function document.getElementsByName returns null and it seems that it can not detect controls inside a contentPlaceHolder.
I used this code for a page that was not using a masterpage and everything went well.
I appreciate any help from you in advance.
Good luck.
Your asp textbox may render as something like:
<input name="ctl00$FeaturedContent$txtBox1" id="FeaturedContent_txtBox1" type="text"/>
So, in javascript, you should use clientid:
<img alt="Calender" src="calender.jpg" onclick="displayDatePicker('<%= txtBox1.ClientID %>', this);"/>

AJAX Control Toolkit Control Editor Javascript Access

In my aspx, I have the following snippet of code, which correctly renders the Editor Control from the AjaxToolkit
<div>
<ajaxToolkit:Editor ID="Editor" runat = "server" />
</div>
In C#, to access the content of the Editor is simply:
Editor.Content = "some text here"
However in JavaScript, I am unsure how to access this. So far, I have tried:
var st =$find('<%=Editor.ClientID%>').get_content();
However the $find statement is returning a null value.
It should work. I tried the following code and editor component was found successfully.
<asp:ScriptManager runat="server" ID="ScriptManager" EnablePartialRendering="true">
<Scripts>
<asp:ScriptReference Path="Scripts/jquery-1.4.1.js" />
</Scripts>
</asp:ScriptManager>
<div>
<ajax:Editor runat="server" ID="Editor"></ajax:Editor>
</div>
<script type="text/javascript">
Sys.Application.add_load(function() {
Sys.Debug.traceDump($find('<%= Editor.ClientID %>'), "editor");
});
</script>
So, try to access you editor in Sys.Application.add_load event handler. If this will help you then the cause of the problem is that you tries to find component before page completes component initialization.
After playing around with this feature, I noticed that the HTML looks like this:
<iframe id = "Some iFrameId">
#document
<html>
<head>...</head>
<body>The text of the editor</body>
</html>
</iframe>
In the ASPX, I did the following to make my life a litle bit easier:
<div id ="myDiv" ClientIDMode="Static">
<ajaxToolkit:Editor ID="Editor" runat = "server" />
</div>
By doing this, I have simplified my problem to become find the iFrame enclosed in myDiv, which contains the HTML of the editor.
To do that in the JS
//get the iFrame
var myIframe = $("#myDiv, iframe") //this returns an array and myIframe[1] is the iFrame, which contains the text.
//get the HTML from the iFrame
var content = myIFrame[1].contentWindow.document.body.innerHTML;
Now content contains, what I was looking for. This is kind of long, and there might be an easier way, but after searching for a solution, I found most of them to be:
do a .get_content or some function call, which didn't work for my case.

How do you output raw javascript in asp.net

I would like to output raw javascript to an aspx response. Using response.write fails because along with the javascript, it dumps all of the other asp.net stuff in the page, for example:
...
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTAxODk4MjA3OWRk9jVlI2KaQPiVjEC+P0OPYGV74vKjJQZuwD6OaHhb+U0=" />
...
Is there anyway to simply output raw text to the output without having all of the other asp.net stuff on the page? I am trying to use the page as follows:
<script src="mypage.aspx"></script>
Where this page contains the javascript this triggers off the aspx page, however chrome doesn't like it for obvious reasons... it expects javascript, but it is getting javascript + markup + .NET injected stuff.
Please no comments on why I am doing this! Working on very specific problem.
Use .ashx Generic Handler. Then you can set context.Response.ContentType = "text/javascript" and just use Response.Write
I'm not sure that I understand your question, but you can try something like this:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "registerSomething", "doSomething = function(){ ... }", true);
You could also disable the viewstate, etc... and remove everything from the aspx file.
<%#Page ... EnableViewState="false" EnableViewStateMac="false"%>
Include nothing else in the aspx file, no runat=server anything. Then write your javascript in the codebehind using response.write.
This will be pretty tough using WebForms. The best way I can think of would be to add MVC to your project so you can have more control over the output. (Yes, MVC and WebForms can coexist in the same project).
This way you can still leverage the .aspx syntax (or the even-cooler Razor syntax) to produce a javascript file, without WebForms adding all of its annoying stuff to your output.
I needed this and this was my solution:
Created a file script.aspx and the content was straight javascript with the header directive of the page. Then in the javascript I was able to insert calls to static methods:
<%# Page Language="C#" ContentType="text/javascript" %>
function someFunction()
{
var someVar;
someVar="<%= MyClass.MyMethod() %>";
}
That returned just pure javascript with the server side insertions as needed:
function someFunction()
{
var someVar;
someVar="Some string returned by my method";
}

Categories

Resources