ASP.Net OnClick vs Function() Handles buttonName.Click - asp.net

What is the difference between using the OnClick attribute of an ASP.Net Button:
<asp:Button ID="btn" runat="server" Text="New" OnClick="enterFunctionHere" />
vs.
using the event directly in the function:
Sub addNew() Handles btn.Click
Thanks!
UPDATE
If I can do both in VB, which is better? Are they equal?

At the least, in the first option, the generated class for the .aspx page is responsible for wiring up the event handler (and thus, requires the event handler to be Protected); whereas, in the second option, the codebehind class is responsible for wiring up the event handler (so the event handler can be Private).
I'm not familiar with how exactly the Handles keyword is implemented in VB.NET, but it may also affect the timing of the wire-up (I know that wiring up an event in a codebehind's OnInit method will wire up the method at a different time in the page cycle than wiring it up through the markup, and a few obscure cases where that matters).
I, personally, prefer using the Handles method (or using += in C# in the OnInit override). This allows the compiler to verify that the methods exist and don't have to be unnecessarily exposed to inheriting classes. Being compiled also helps when using refactoring tools, looking up usages, etc.

There's no appreciable difference. Both are equivalent to using the AddHandler keyword. Using the OnClick attribute is more compatible with ASP.NET code that might use C#, while using the Handles keyword is more compatible with Windows Forms VB.NET code.

Both add an event handler. Handles is available in VB.Net, not C#.
Also, you can add an event in code with the AddHandler method of a page.

The first one is an example of how pages using c# code behind register the event to the function. This one then needs a method matching the definition.
The second one is the vb.net way of attaching the event to a function.

Related

What is the best way to programmatically run javascript when an ASP.net page loads?

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

When should you use Page.DataBind() versus Control.DataBind()?

In ASP.NET, you can bind controls individually (i.e. GridView1.DataBind()) or you can call Page.DataBind() to bind all controls on the page.
Is there any specific difference between the two calls? Are there times when one should be preferred over the other?
Page.DataBind is Control.DataBind. Neither the Page class, nor the TemplateControl class overrides Control.DataBind.
Control.DataBind does little more than call OnDataBinding for the control, then it calls DataBind for each child control.
For choosing between Page.DataBind() versus Control.DataBind(), here is the Microsoft guidance :
"Both methods work similarly. The main
difference is that all data sources
are bound to their server controls
after the Page.DataBind method is
called. No data is rendered to the
control until you explicitly call
either the DataBind method of the Web
server control or until you invoke the
page-level Page.DataBind method.
Typically, Page.DataBind (or DataBind)
is called from the Page_Load event."
There will be cases when you want specify control databinding individually, depending on the current page scenario. For a detailed level of control over which controls are bound and when controls are bound, I opt for the control-level DataBind() methods.
In an ASP.NET page, you can bind directly to public/protected properties of your page's code-behind class. For example:
<form id="form1" runat="server"><%#HtmlUtility.HtmlEncode(MyProperty.ToString())%></form>
In this case, there is no specific control to call .DataBind() on - the page itself is the control. It just so happens that calling Page.DataBind() will also call DataBind() on all child controls, so if you're already doing a Page.DataBind(), there's no need to data bind the controls individually.
This is not a direct answer to subtilities between the two calls, but
about DataBind() vs Page.DataBind() I would like to share an interesting experience which may also really guide you to chose between both :
I just spent one complete day to figure why Ajax calls and events in a huge webapplication were broken (ItemCommand not raised on callbacks and postbacks, lost references, etc).
The reason was I had one ASCX which made a call to Page.DataBind() rather than DataBind() on itself.
It could seem obvious when you found it, but when you are dealing with weird behavior in a >500000 lines application and a lot of complexity in master/pages/controls, it's not.
So beware of Page.DataBind() if you call it at the wrong place !

What is the best way of subscribing to events in ASP.NET?

I've done some reading on SO, but didn't find the answer to my question.
As #Canavar points out in his answer there are 2 ways to subscribe to an event:
Declarative:
<asp:Button runat="server" ID="myButton" OnClick="myButton_Click" />
Code Behind:
myButton.Click += new EventHandler(myButton_Click);
I subscribe to events declaratively, but hardly ever use the "sender" and EventArgs in default event handlers. Most of the time I end up calling a method from the event handler.
Would it be better to subscribe to events using a delegate?
myButton.Click += delegate{DoStuff();};
Let me know if I'm over complicating things, and should stick to declarative event subscription, and calling my DoStuff() method from default event handler.
Your handler needs to match the event's specified params. If you use a delegate you will just be defining the same thing. Discarding the params seems like a waste since you might need them in the future for some reason. I can't think of any good reason to not want the parameters.
And an event handler is a delegate already :)
I personally use the declarative approach whenever possible. While neither the declarative nor imperative approach is really "better" than the other, both have their merits. For the most part, using the declarative approach means you have greater decoupling and more flexibility between page behavior and page content. If you, for whatever reason, need to change you're page content around, using the declarative approach gives you more leeway to do so without requiring a recompile.
That does not mean the imperative approach is useless. There are times when it is not possible to apply handlers declaratively. Namely dynamic scenarios. The imperative approach allows you to use code to create dynamic content and still wire up events. Use what fits the scenario best. There is no one proper approach, both have their niche.
My favorite:
myButton.Click += myButton_Click;
The EventHandler is not actually needed. Also, if you are C# 3.0, you can go lambda on it:
myButton.Click += (x,a)=>DoStuff(); // something like that.
But really, it isn't worth worrying about too much.

Why do WebControl events have the prefix of "On"?

I'm trying to fully understand the WebForm event model (not the page lifecycle, but how the events are wired up when specified declaratively in the .aspx or .ascx files.
Take the Button control for example. It has a Click event that you can wire to in the code-behind, but it has an "OnClick" event in the .aspx/.ascx file.
I used the .NET Reflector and the Button control has a PROTECTED OnClick method, but that shouldn't be available to be assigned by the .aspx/.ascx. Unless I'm missing something.
Does anyone know why the "On" prefix is added?
Just to clarify a bit: I understand the naming convention works. I'd like to know how the "OnClick" in the .aspx/.ascx gets translated into .Click += new EventHandler(blahName); I.e. if I create a ControlChanged EventHandler, do I need to do anything special to get the OnControlChanged to show up validly in the .aspx/.ascx file?
Those store references to the delegates that the calling code will be wiring up using events; in order to distinguish between the event itself, and the delegate.
It's more than a naming convention because events in user controls automatically get the "On" prefix in the declarative syntax.
For example, I have a UserControl that declares a ProjectSelected event. To add a handler declaratively, I set the OnProjectSelected attribute.
UserControl:
public event EventHandler<ProjectSelectedEventArgs> ProjectSelected;
Adding handler declaratively:
<user:ProjectList id="uxProjectList" runat="server"
OnProjectSelected="uxProjectList_ProjectSelected" />
Adding handler in code behind:
uxProjectList.ProjectSelected += uxProjectList_ProjectSelected;
This confused the hell out of me twice, once when I couldn't figure out why the event wasn't available declaratively, and again when I named the event "OnProjectSelected" and the attribute became "OnOnProjectSelected".
It's just a naming convention used when raising events. OnSomethingHappened ... OnClick, OnChange, OnClose. I don't think there is anything magical or sinister, it's just a convention.
Semantically it is basically an old throwback to VB traditions where event listeners were generally called OnWhatever. Old habits die hard.

Using AJAX callbacks with ASP.NET User controls

What's the best way to implement user controls that require AJAX callbacks?
I want to accomplish a few things:
Have events done in the browser (eg, drag and drop) trigger an AJAX notification that can raise a control event, which causes code on the page using the control to do whatever it needs to do (eg, change a value in a database).
Have partial updates (NOT using an updatepanel) that can do things like populate an auto-complete dropdown underneath a textbox.
Implement a single user control that is generic enough to be reused on several pages
Avoid having to implement logic on the page itself that passes events back to the control, because that is repetitive and hard to maintain
I'm using jQuery for most of the client side stuff, but for the actual AJAX calls I don't really care if it's jQuery or the ASP AJAX libraries.
Effectively what would be perfect is PageMethods on the user control, that would be easily callable from client-side script. Unfortunately, as far as I'm aware, pagemethods do not work on user controls.
I'll use an autocomplete control as an example:
I should be able to put the autocomplete control on the page, and then in the page code, have eg:
Public Sub HandleLookup(ByVal input As String, ByRef list As List(Of String) Handles MyControl.LookupEntries
list = New List(Of String)
' Query database for list of items..
For Each item as String in FullItemList
If item.StartsWith(input) then list.Add(item)
Next
Return list
End Sub
And do nothing else .. the rest of the code should be in the usercontrol.
Note, the controls I'm trying to make are much more specific than eg, autocomplete. They do not exist in any 3rd party libraries and I really need to be able to make them myself.
Look into implementing ICallbackEventHandler in your Page -- it's a simple way to make a call back to a page function from JavaScript.
Here's a good tutorial:
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=119
You might want to check out; Ra-Ajax UserControl Sample and combine that knowledge with Ra-Ajax Drag and Drop
Click the "Show code" C# icon to the left to see the usage of the code...

Resources