I have a problem with jquery not loaded in an asp user control.
I want simply to add the click event when a checkbox is clicked.
Here is my javascript file
$(document).ready(function() {
var arr = jQuery(":checkbox[id*='drpAccountType']");
for (i = 0; i < arr.length; i += 1) {
$("#" + arr[i].id).click(function() { alert(this.id) });
}
});
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
The user control pre render events:
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
ScriptManager.RegisterClientScriptInclude(Me, Me.GetType, "CheckboxdropdownScript", ResolveUrl("~/Scripts/CheckBoxDropDown.js"))
End Sub
the script is loaded fine but any usage of jQuery return undefined. Then only when the page is loaded I can excute the same code for the commande line in firebug. The jquery library is loaded in the master page.
Whenever I'm using jquery within an asp user control I always find problems, and I always have to hack around to get it to work. I try all the entries in stackoverflow but I never found a one as general solution.
did any one found a simple solution to use jquery with master pages, user control in asp.net
I would appreciate if someone can share such valuable information.
My manager is about to drop jquery from the application as we always waist lot of time just to find a workaround to have it to work with user controls.
Please help, I like jquery and I really want to use it for client script.
best regards
your script may be getting inserted into the page before the jquery library. (You can verify this by checking the HTML output of your page.)
When script files execute JS inline, and especially when that JS depends on other libraries, it's safest to use RegisterStartupScript rather than RegisterClientScriptInclude. If you use this overload of RegisterStartupScript, you can construct a reference to the same external JS file and it'll run in the right place.
As an alternative, you could use <asp:ScriptReference/> tags in a ScriptManagerProxy in your user control rather than registering the script in Page_Load or Page_Init; in my experience, those scripts are added after scripts from the master page.
this is not exactly a direct answer but here are some jQuery ASP.net controls that might help:
http://clipperhouse.com/jQuery/
(Look for the bit about Callbacks.)
Also, you might not need the "for" loop if you simply give all your checkboxes a class name and use that as the selector.
Related
I'm new to web development, and I'm currently using ASP.net. I wonder what would I need to do to let the browser wait for 3 seconds so my users can read the text "Customer Successfully Added" before turning to another page? I have attached my code as follows.
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim db As New DatabaseClass
db.addProfile(txtLN.Text, txtFN.Text, txtUsername.Text, txtPassword.Text, txtAddress.Text, txtZip.Text, txtPhone.Text, txtEmail.Text)
lblMessage.Text = "Customer Successfully Added"
End Sub
In addition, I'm not sure how to utilize MSDN. For me, its information overload, I'm wondering how to go about finding the solution on MSDN so i would be able to solve my problems in the future. Thank you!
You can't do it in the code behind of the page because of how asp.net works - the label text would not update until after the timeout occurred if you did it in the code-behind.
The server-side processing spits all the html back to the browser only after it has completely processed any server-side code unless you're using Ajax. Since you're new, I won't even bother going into how to do it with Ajax as there is a MUCH simpler option for accomplishing what you want.
A simple method to accomplish what you're looking for would be to have a simple HTML page that just has a message that says "Customer successfully added" and use javascript (client-side code) to pause and then redirect using the Javascript "SetTimeout" function.
There's an example here: http://www.bloggingdeveloper.com/post/JavaScript-Url-Redirect-with-Delay.aspx
The logic flow wshould work like this:
The original page should add the record (in code-behind) then redirect to this simple html page (in code-behind). The html page should have the "Customer Added" message and use the SetTimeout and Redirect to go to whatever page you want the user to see after viewing the message.
For stuff like this you need the code to run client side rather than on the server. The easiest way to do this is to return some javascript with your page (in the .aspx part rather than the code behind)
Take a look here for an idea of what to do :)
The page is displayed for a few seconds and then the javascript triggers a redirect to a url of your choosing. Just add something like this into your html.
You can emit javascript to redirect to the other page, using the setTimeout function.
This is best accomplished using the ScriptManager to register any javascript on the page.
In my global.asax file for my ASP.net project, I am checking for certain conditions. When those conditions are met, I want to automatically execute javascript code when the page runs.
This is my code:
if condition Then
Response.Write(" < script type=""text/javascript"" > ")
Response.Write(" // Javascript code to do stuff ")
Response.Write(" < /script > ")
End If
While this appears to work to execute the Javascript code, I don't think it's a best practice because this code will preceed all of the HTML of the page that gets loaded.
What is the best way of programmatically tacking on some extra Javascript code to be run when my page loads?
Update Thanks for the answer. Too bad this solution doesn't work from within global.asax. Is there no way to make this happen site-wide? It seems like global.asax would be the logical place to put code that runs with every page... Response.Write works fine in global.asax.
To correctly manage the placement of scripts from server controls or pages, you should use ClientScriptManager.RegisterStartupScript()
You can also use the equivalent method in the ScriptManager if you are using ajax controls in your site: ScriptManager.RegisterStartupScript
These methods take care of outputting your script in the appropriate locations to be run when the document is finished loading. The links posted have some good examples to work from.
Note that you won't be able to use these methods directly from global.asax, as it has no reference to the current page. Global.asax is for hooking events to the HttpApplication pipeline, and is decoupled from the actual HttpHandler such as your Page object. To keep the separation of UI, you'd be better off to do the check in your master page or in some base page class, and output the script from there.
back in the days of asp.net ajax 1.0 we had something called Sys.WebForms.PageRequestManager in the ajax client libraries. Haven't worked with asp.net 3.5 and asp.net ajax, but I am sure it is simply enough to add the asp.net ajax javascript file into your page and you'll be able to make use of it. Check out for an event called pageLoaded event.
ps: this event will fire every time there is a sync or async postback
If you want to do it on every page, put it on your masterpage if you have one.
If not, you can create a base Page class, that inherits from System.Web.UI.Page and extend it to check your conditions & render javascript.
Then in the codebehind of each page, inherit your base Page Class instead of System.Web.UI.Page
public partial class Orders : MyCode.BasePage
I have an external javascript on my page, e.g. something like:
<script src="http://foo.com/script.js" type="text/javascript"></script>
and an UpdatePanel somewhere. The script writes some content, and does this from within an anonymous javascript function in the js file. I.e., there is something like this in the script:
(function(){document.write('content');})();
Whenever the UpdatePanel is updated through asynchronous postback, everything the script did (or any javascript on my page, for that matter) is made undone.
For normal javascript, I would just use:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(myFunction)
to redo all that, but since the function in the script source file is anonymous and called upon definition, I'm SOL! Any ideas?
Note: the external js source is from another domain and its content is out of my control.
Try this
private string _myScript = #"(function (){
var ys = document.createElement('script');
ys.type='text/javascript'; ys.async=true;
ys.src='http://foo.com/script.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ys,s);
});";
Then in your Page_Load
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myScript", _myScript , true);
Ok, the "solution" ("dirty ugly hack", if you prefer) I came up with:
Instead of loading the js file directly, I load it via a wrapper that reads the file, wraps the result in custom javascript that puts the anonymous function in a global array, and call all functions in said array upon load and after each asynchronous postback.
Please don't enter this solutions in any beauty pageants.
The real problem here was that I wasn't using UpdatePanels correctly. If the UpdateMode of all the UpdatePanels on your page are set to Conditional, and your ScriptManager has partial updating enabled, it really shouldn't "[undo] everything the script did".
I am trying to make use of the yahoo exceptional performance rule : avoiding duplicate script
To do so i would like to be able to know whether or not a script was already added to the page before injecting it in the page. It looks like i can't figure what has been added in asp.net code behind unless i have a scriptmanager added to the page. but i would like to avoid using asp.net AJAX. From the description of the rule, it looks like it is something possible in php though.
Assuming that i can't do the check in my code behind, i was considering using jQuery $.getString function but it doesn't check before fetching the script. If i was to choose the javascript file, would i have to parse the whole http response in order to figure out which script was loaded on the page?
If the page is registering the scripts with the ASP.NET Page.ClientScript Register APIs then you can use Page.ClientScript.IsClientScriptIncludeRegistered. On the other hand, if you are using those APIs you don't really need to call it, since it already ensures only one of each is registered.
http://msdn.microsoft.com/en/us/library/system.web.ui.clientscriptmanager.isclientscriptincluderegistered.aspx
If the page just has regular ole script elements statically in the markup, and you need to detect if a script is loaded on the client side, you will have to get all the script elements on the page and look at their .src values. The thing with that is that some browsers automatically resolve that url to a full path, not just the one you declared. So, you can account for that in various ways -- you can just search for the end of the string being the script you want, or you can cause the url you want to compare with to also be resolved by setting it onto a dynamically created script element (which you never add to the DOM but is still resolved for you).
This is just off the top of my head, sorry if I get something wrong:
var s = document.createElement("script");
s.src = "foo.js";
var loaded, scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src === s.src) {
loaded = true;
break;
}
}
if (loaded) {
// this script is already loaded
// assuming you dont have multiple copies in different locations
}
You don't need to use any client-side scripting to do this... you can do this in your code behind using the ClientScriptManager without needing to make use of ASP.NET AJAX (I think you're confusing ClientScriptManager with ScriptManager*) in your control/page just use:
ClientScript.RegisterClientScriptInclude("some-script", "myScript.js");
or from your user controls:
Page.ClientScript.RegisterClientScriptInclude("some-script", "myScript.js");
This will use the key "some-script" & only register one copy of the script on the page.
*To be clear I think the confusion is arrising from the difference between these:
ClientScriptManager if a server-side helper class which is used to manage client side scripts (in other words its whole purpose is to do exactly what you are trying to do). It is accessed via the Page's ClientScript property.
ScriptManager is a Control used to aid client side Ajax scripting in ASP.NET AJAX
(hell I even confused myself & gave the wrong example code initially)
well that wouldn't actually work in a master detail scenario with multiple web user controls.
Then you wouldn't have control over who has to do the script initialization if the web user control is dynamic.
It's easier to link once, but a developer would have to weigh his options between ClientManager and using a script load.
yeah you have to parse the whole response...
why don't you create a javascript file and put all of your javascript there and then import that javascript file in your code??? in this way you can get rid of duplicate script insertion.
I have a composite control on an ASPX page. There is Javascript on the ASPX page that gets loaded before the control. Now, since the script refers to the control element which does not exist when the script is loaded, this is throwing a Javascript error of "Obect not defined". Attaching the script to the onload event of the control gives "Sys not defined".
Any Idea?
The script is in an external file.
You need to either move the Javascript function below the control creation, or add it inside a window.load event handler (jQuery and Prototype can help you for that), so you guarantee that the Javascript is called when the page has loaded and not before.
You can keep the script in the load method of your control, although really it should be placed in the PreRender because then you can include it or not include it based on the state of the control. This would save you from javascript errors in the future where it says "Object cannot be found" because you have made the control invisible.
The reason you're getting "Sys is not defined" is because your script is being placed before the MicrosoftAjax.js file has loaded. Try something like this:
Dim yourScript as String = "Sys.Application.add_load(function() { /*code here*/ } )"
ScriptManager.RegisterStartupScript(Page, Me.GetType(), "ScriptKey", yourScript, true)
Otherwise you could use Page.ClientScript to hook into the document ready event if using the Sys namespace is not a requirement, but it sounds like from your question it is.
Edit:
Instead of RegisterStartupScript you're probably looking for RegisterClientScriptBlock, sorry, the two have different functionality.