开发者

Subscribing to Event Handlers

开发者 https://www.devze.com 2022-12-24 23:08 出处:网络
I\'m curious about the pros and cons when subscribing to event handlers. <asp:DropDownList id=\"DropDownList1\" runat=\"server\" OnSelectedIndexChanged=\"DropDownList1_SelectedIndexChanged\" />

I'm curious about the pros and cons when subscribing to event handlers.

<asp:DropDownList id="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />

vs

protected void Page_Init(object sender, EventArgs e)
{
    this.DropDownList1.SelectedIndexChanged += new EventHandler(DropDownLis开发者_StackOverflow中文版t1_SelectedIndexChanged);
}


From the technical point of view, there aren't any big differences between the two, so it is a question of coding style and personal preferences. Here are a couple of points that you can consider:

  • The declarative approach using the ASP.NET markup is usually shorter and you don't need a large method that does all the initialization
  • If you initialize handlers in the code-behind you don't pollute the declarative markup with aspects relevant only for the code-behind (though I don't think this is a big issue)

In some cases you can use features such as C# lambda expressions nicely in the code-behind:

protected void Page_Init(object sender, EventArgs e) { 
   this.btnNext += (s1, e1) => MovePage(this.CurrentPage + 1);
   this.btnPrev += (s2, e2) => MovePage(this.CurrentPage - 1);
   // ...
}

Something like this can reduce the number of single-purpose event handling methods that you need to write, which should make the code-behind simpler.

However, I think that the general recommendation for simple ASP.NET applications is to use the declarative event handler binding, unless you have some good reason for not doing that (e.g. as in the example above).


One difference is in compile time checking. If you use the declarative method and for some reason you change the handler method name or signature you won't know it until the ASP.NET run time processes the page. If you use the explicit binding in the code-behind then you'll get a compile time check on it. A bit more stable.

Also, some will likely argue that putting the event handlers in the markup contradicts the rules of separation of concerns. Although with ASP.NET web forms, there's still a bit of crossover unlike the discreet separation found in the MVC framework.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号