What is the best way of subscribing to events in ASP.NET? - 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.

Related

Behavior vs Event Handler

What's the purpose of having behaviors in Xamarin.Forms? Isn't it possible to add new functionality to UI elements through event handlers? I am confused about when to use an event handler and when to use behaviors.
This is a very simple answer and is only intended to start your research. Undoubtedly a better answer will come along. I am still working through this and will keep an eye on it because I too would like an answer that is more thorough than mine.
With proper separation of your View and ViewModel, Events aren't really the way to go. Behaviors allow you to maintain a proper MVVM approach (for example, when calling a Command from an Entry's Completed event) by using an EventToCommandBehavior system.
Additionally, Behaviors allow you to create prepackaged, well, behaviors that can be applied to multiple controls' events without having to reuse code.

best way to reference event arguments in asp.net

Best practices question.
While I was writing some event handlers, I ran into an issue where I as looking at the incorrect event (GridViewRowEventArgs) when I should have been looking at something else.
Now to solve my problem, instead of referencing the very specific event I was looking at, I just used EventArgs, which seems to catch any possible event. So, finally to the question; is there an issue with using EventArgs instead of the specific event? is it better to use the specific one for debugging issues? What is everyone's opinion?
Thanks
If a control is compliant then their event arg classes will always inherit from the generic ASP-provided EventArgs, which is why your approach works. Ultimately, if you don't need the extra information provided by the control through their own custom event arguments class then obviously you can dispense with using it altogether.
However, from a best practice perspective, my feeling is that it would be better to use the correct handler signature provided by the control, since that makes it predictable to people who might be working on your code and can't read your mind, but do have access to the the particular control's documentation.

Is it OK to use __doPostBack()?

Is it OK to use __doPostBack() or it is not recommended because it is generated from ASP.Net and we are not sure if they changed it in a next version of ASP.Net.
I would advice against it, since it's internal stuff of ASP.NET and was never meant to be used directly.
Instead, what I'm doing when I need to "manually" trigger PostBack is adding hidden "server side" button with the proper OnClick:
<asp:Button id="btnDummy" runat="server" OnClick="Foo" style="display: none;" />
Then the JS is:
document.getElementById("<%=btnDummy.ClientID%>").click();
This way I don't care how post back happens, I just trigger the natural flow of events.
You should not call it directly. You should generate the javascript call by using functions in Page.ClientScript such as:
GetPostBackEventReference
GetPostBackClientHyperlink
This will ensure that it's always compatible.
I think its perfectly fine to use directly, and have used it without fail, its just a javascript function after all.
They probably won't change it, but why call it directly?
I think it's a better strategy to trigger the event (a button click for example) and let the control trigger the postback.
I you do need to trigger the postback directly it's recommended to use the Page.ClientScript functions tenfour described.
We use it all over the place and I can't imagine it would ever be stripped out of ASP.NET. I think the fake/hidden button method is just as hokie if not worse. If you use the fake button approach, then you get no option to pass in the __EVENTARGUMENT. I like using __EVENTARGUMENT to pass my data to the server better than creating hidden fields, because it would be more difficult for a hacker to compromise than simply posting back some hidden field to my page. I also don't like the idea of creating fields and controls on the page if they are not even going to be displayed. I am sure that the fake button approach is probably easier for a newbie coder to understand. That being said I am searching for a more elegant way to approach this, but still find myself calling
__doPostBack('%=UpdatePanel.ClientID%>','MyData')
in some cases.

Custom SelectedValue attribute

I am creating a completely custom (only inherits from WebControl) combobox/dropdownlist search control with autoComplete capabilities.
JQuery handles assigning the onhover and onclick events for list items (divs with strings in them) and handles the web service call for getting the list of items for the matching text.
The server handles the custom attributes and control rendering.
The issue is that I need to implement a property that is similar to SelectedValue so that when a user selects an item from the search results, the value can be used on the server for other processing. I have done days of research but have not found a clear, concise way of handling the post back data.
I did read a blog that mentioned implementing the IPostBackDataHandler interface, but the implementation of RaisePostDataChangeEvent() calls for calling a server method (like SelectedIndexChange) that I am not implementing at the moment.
public void RaisePostDataChangedEvent()
{
this.SelectedIndexChanged(EventArgs.Empty);
}
Now for the question: Does anyone have advice for handling this? Or am I better off simply inheriting from the dropdownlist control and overriding the existing functionality?
I feel like I'm missing a very small piece that will fit this all together.
Have you considered pulling down the source code from Microsoft's source server and taking a look at how they implemented DropDownList? This would allow you so see how they solved the binding and events part of the problem and give you a good idea what it does otherwise. This way you can decide if you want to inherit from it, or if you can just borrow some ideas for how they implemented IPostBackDataHandler.
Since I have no idea what specifically you are doing, I couldn't advise you if you should inherit from dropdown as it is, but based on my impressions of what you are doing I'd say you probably don't.
Also you might look at source from the AjaxControlToolkit as it has a similar component. Again, you can get ideas for how these specific things are handled and adapt them to your own needs.

Calling base Methods When Overriding Page Level Events

In my code behind I wire up my events like so:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnUpdateUser.Click += btnUpateUserClick;
}
I've done it this way because that's what I've seen in examples.
Does the base.OnInit() method need to be called?
Will it be implicitly be called?
Is it better to call it at the beginning of the method or at the end?
What would be an example where confusion over the base method can get you in trouble?
I should clarify:
The guidelines recommend that firing an event should involve calling a virtual "OnEventName" method, but they also say that if a derived class overrides that method and forgets to call the base method, the event should still fire.
See the "Important Note" about halfway down this page:
Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
In this case, if you don't call the base OnInit, then the Init even will not fire.
In general, it is best practice to ALWAYS call the base method, unless you specifically know that you do not want the base behaviour to occur.
Whether its called at the start or the end depends on how you want things to work. In a case like this, where you are using an override instead of hooking up an event handler, calling it at the start of the method makes more sense. That way, your code will run after any handlers, which makes it more emulate a "normal" event handler.
Although the official framework design guidelines recommend otherwise, most class designers will actually make the OnXxx() method responsible for firing the actual event, like this:
protected virtual void OnClick(EventArgs e)
{
if (Click != null) Click(this, e);
}
... so if you inherit from the class and don't call base.OnClick(e), the Click event will never fire.
So yes, even though this shouldn't be the case according to the official design guidelines, I think it's worth calling base.OnInit(e) just to be sure.
official framework design guidelines recommend otherwise
They do? I'm curious, i've always thought the opposite, and reading Framework Design Guidelines and running FxCop has only cemented my view. I was under the impression that events should always be fired from virtual OnXxx() methods, that take an EventArgs parameter
You probably are better off doing it that way, then this debate goes away. The article is interesting though, especially considering that the .NET Framework doesn't honour this guideline.
#Ch00k and #Scott I dunno - I like the OnEventName pattern myself. And yeah, I'm one of the people who are guilty of firing the event from that method.
I think overriding the On* method and calling the base one is the way to go. Handling your own events seems wrong somehow.

Resources