Using Javascript With ASP.Net controls - asp.net

Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.
Are these the only two choices? Is there a right way to do this that I'm missing?
Thanks!
Eric Sipple

**just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.
Every ASP.NET page (2.0 and greater) comes with a ClientScriptManager. You use this to register javascript from server side code. You can pass in javascript that registers events on controls after the page has loaded, when the HTML controls on the page are all present in the DOM.
It presents a single, unified place on pages to dynamically add javascript, which isn't a bad thing. It is, however, awfully ugly.
In this time of the death of the ASP.NET server control model, you might want to set events the way they will be in the future of ASP.NET MVC. Grab a copy of jQuery and add it to your website. You can then easily register your events thusly:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("controlId").bind("click", function(e) { /* do your best here! */ });
});
</script>
</head>
<!-- etc -->
</html>

You can add the events through Javascript to the HTML elements that you want. This is the cleanest way, since it doesn't mix the server&client technologies. Furthermore, this way many handlers can be registered to the same event (in contrast to the onclick attribute).
Basically, the code would be
document.getElementById('myLovelyButtonId').attachEvent('onclick',doSomething)
for Internet Explorer and
document.getElementById('myLovelyButtonId').addEventListener('click',doSomething,false)
for other browsers. (doSomething is an event handler - JavaScript function). These calls should be made in the window load event handler
Consider reading the advanced event registration article on Quirksmode for further info.
Also, consider using a library like jQuery. This way, the statement will become
$('#myLovelyButtonId').click(
function doSomething () {
alert('my lovely code here');
});

Setting the value for WebControl.Attributes["onclick"] is okay. If ASP.NET needs a client-side click handler, it will concatenate the values, delimited by semi-colon.

Fix grammatical or spelling errors.
Clarify meaning without changing it.
Correct minor mistakes.
Add related resources or links.
Always respect the original author.

Related

ASP.NET Web User Control Positioning on Page

I'm an experience programmer who is writing his first asp.net application.
I needed a pop up calendar and didn't like the javascript based ones I found.
I wrote my own Web User Control thinking that would be best. (I still have some issues with it). I used a textbox, image button and the asp.net calendar control.
The control works reasonably well, but not being an HTML/ASP programmer when I placed it on my page, whenever I clicked the button to display the calendar, my page goes horribley misaligned. I placed it inside of a HTML table and that helps. But I was wanting to not worry about control alignment on the page.
Am I completely misunderstanding how a Web User Control would display for this time of calendar control?
Should I abandon my work and look for a Javascript solution? (But if it's a user control won't it do the same thing?
While this is a good item to learn with it certainly has been done, and done very well in many places.
Any server based calendar control is not your best option, it will lead to a postback anytime you are switching from month to month, which is less then ideal.
jQueryUI is a great/simple option to get a calendar control that will not mess up your other layout.
In the end if you still want to implement your control we will need to see some HTML/CSS as to why it is messing up your UI.
It's worth spending some time learning how jQuery UI and the datepicker() plugin work. I'm guessing by your original post that you are not too keen on a client side solution, but I rarely see a need for a server side calendar control.
Javascript/jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#myTextBox").datepicker();
});
</script>
HTML
<script type="text/javascript" src="<jQuery URL GOES HERE>" />
<script type="text/javascript" src="<jQueryUI URL GOES HERE>" />
<input type="text" id="myTextBox />
Apologies if the syntax is a bit off... I dont have VS in front of me to test but hopefully it should give you an idea where to start :)

Ajax Toolkit Client Rendering

I'm working on a long, dynamic form (100 or so fields) and am using toolkit items such as CalendarBehaviors, HovermenuBehavior, etc for each field.
I've never worked with that many toolkit items at once, and am seeing a big performance hit in rendering. Every instance of a toolkit control is being sent to the client in its' own <SCRIPT></SCRIPT> tags. In other words, 200 instances of he following:
<SCRIPT type="text/javascript">
Sys.Application.add_init(function() { $create(AjaxControlToolkit.HoverMenuBehavior, {"OffsetX":20,"PopDelay":50,"dynamicServicePath":"/default.aspx","id":"hmePopupHelpPolicyNumber","popupElement":$get("lblHelpPolicyNumber")}, null, null, $get("imgHelpPolicyNumber"));});
</SCRIPT>
<SCRIPT type="text/javascript">
...snip
</SCRIPT>
Is there any way to control this and have all the controls created in a single script block?
Also, does anybody know of a good, detailed article that would describe how IE 7 parses and renders html and javascript?
And I know most of you will recommend JQuery instead. Unfortunately that is not an option in this project.
Thanks in advance and happy coding.
I'd say rethink your design of the page. That many items on your page can't make for a good user experience. Instead of coding a really far out solution, reconsider your design and it will probably benefit your user in the end as well.
Edit:
Your question is at the heart of what many consider the major drawback to using WebForms. There is little control on how the server renders the controls and emits their HTML. Without a more "advanced" approach which you are trying to avoid, I'd be hard pressed to suggest anything other than breaking the form up into smaller pieces. If it is a data entry form, it may be faster for the user to type in the date fields as opposed to populating the form via mouse clicks.
Going along the lines of #Achilles' answer, I would break up the form into multiple pages. You could also try one page with multiple tabs.
Update:
Something else that might help you is the ToolkitScriptManager. It combines all of the external toolkit scripts into one single external script. I think it also combines all of the inline toolkit scripts into one block.

How do I temporarily convert an ASP.NET Ajax form to not use partial page updates?

I need the ability to temporarily turn off the partial page update behavior for an ASP.NET Ajax / UpdatePanel based page. (The reason is to circumvent the issue where IE blocks "automatic file downloads" for downloads generated as a result of this postback, but I don't want to distract from my original question)
I looked at the client side javascript libraries hoping to find a switch somewhere. I think a solution might involve using javascript to override the 'onclick' event handler for the control that acts as the trigger, and then calling "submit" on the form itself..
Also, using the EnablePartialRendering property on the server-side ScriptManager control won't work because that is done when the page is being built. I need to be able to do this as a result of switching a drop down list box.
Any ideas?
Cheers!
/ Sean
Well, after much trial and error, I found two approaches that seemed to work:
Use Javascript to manually submit the top level form associated with the page. This usually has the ID of "form1".
Create a button that is outside of any UpdatePanels and use Javascript to click the button.
I wound up using the second approach, since it allowed me to handle the event with a specific routine without the need to guess that my postback came from a Javascript call.
This is an example of the code that performed the postback:
...
if (isDownload) {
document.getElementById('FullPostbackSubmitter').click();
return;
}
...
Hope this helps someone else!
You can set the EnablePartialRendering property of your ScriptManager to false.

Register Startup Script Control

I am looking to make a web control where I can register client startup scripts inline with my aspx because I hate registering in the codebehind!
An example of what I have so far:
<Ben:StartupScript runat="server">
var form = document.getElementById("<% =form1.ClientID %>");
</Ben:StartupScript>
Currently, I am overriding the OnPreRender method of the control, rendering the contents of the control to a string and then manually registering that string as a startup script using ClientScript.RegisterStartupScript on the Page. I also override the Render method in order not to render the control. I should also note that I have the ParseChildren attribute set to false and the PersistChildren attribute set to true.
All seems to be working well, but my control allows other web controls inside it (such as Button). Apart from being unintuitive, this can result in runtime errors. I would love to be able to clear the controls but this is impossible given the <% ... %> code block.
So, is it possible to prevent developers from embedding child controls whilst still allowing code blocks?
Also, is this idea any good or is it fundamentally flawed? Lol.
Thanks a bunch,
Ben
it sounds like a good idea, but if you spend too much time fighting the inherited/default behaviors then it may be more trouble than it's worth
if this is a one-shot issue, a cheap-hack solution is to just directly embed your scripts in the header of a master page ;-)
on the other hand, allowing developers to embed their own scripts as children of your web control might be useful
If you are using master pages, add another control in your section. That way you can easily add css/js to your headers in your child pages.
ClientScript.RegisterScript is mostly for user/server controls,

jQuery Validation plugin and ASP.NET validators Web Forms

I would really like use the jQuery Validation plugin in my ASP.NET Web Forms application (not MVC).
I value jQuery validation for the Richer UI experience I can provide the end user and I have some requirements to highlight the invalid fields using a red border (css).
I value asp.net validators because they run the validations not only on the client but on the server so that I don't open various security vulnerabilities to any user who is clever enough to turn off javascript in their browser.
So I am looking for a nice clean way to integrate these two technologies.
The best I can come up with is to have all ASP.NET validators set to enableclientscript=false and repeat the validation rules on the client in jQuery and on the server as asp.net validators but I can already see some challenges with this approach.
In the end I found the lowest friction way to achieve highlighting with asp.net validators and jquery was not to use the jQuery Validation plugin but to use the simple line of jquery which follows (note that the exact syntax will vary depending on how you layout your forms):
<script type='text/javascript'>
$("input[#type=submit]").click(function() {
$('span.validationerror:hidden').parent().parent().find('input').removeClass('inputError');
$('span.validationerror:visible').parent().parent().find('input').addClass('inputError');
});
</script>
You can use asp.net and jquery validators together with no problem... even on the same control... you just need to set CssClass for the control so that jquery can find it... and then you add OnClientClick="return $('#aspnetForm').valid();" to your submit button(s).
Be sure and include the usual jquery library and jquery.validate.js and add a document ready function of course, etc.
This might help!
http://www.delphicsage.com/home/blog.aspx?d=205
If you are serious about validation, I would look into something like Peter Blum's validators (http://www.peterblum.com/Home.aspx) as they should be able to do everything you want and more. They don't use JQuery, but remember the whole point of JQuery is to save developer time - the end user doesn't know or care whether you are using JQuery or not if the overall effect is the same.

Resources