开发者

To bind or do not to bind

What's the difference between these code samp开发者_如何学编程les? Which approach is right?

 <asp:Label ID="lblShorName" runat="server" Text="<%#Customer.ShorName%>" />
 lblShorName.DataBind();

and

lblShorName.Text = Customer.ShorName;


There isn't much of a difference that I know of (though I'll be interested in other people's answers to correct me if I'm wrong on that). It's just a matter of coding style and preference.

Personally, I prefer the latter. I feel that it's cleaner and separates the markup from the functionality which drives the markup. But that's just me.

(I also tend to prefer not using data binding where I don't feel I need to. But, again, it's a preference of how you want to use the tooling that's provided. For example, in an ASP.NET MVC view I'm more likely to write a loop and output HTML within that loop than I am to use any kind of repeater or grid control and bind data to it. Just personal preference.)

A lot of it also comes down to where in your application you want to perform these actions. The former example keeps it on the page, whereas the latter example can be wrapped in conditionals, re-factored into another method, etc. If it's possible that the value in question isn't always going to come from Customer.ShortName then I'd go with the latter example to add that additional logic around it.


The approach depends when you want to set the label. lblShorName.Text = Customer.ShorName; Can be used in different methods, events, timers. If you want to set it only at the beginning you can use the first one.


Not much really, when you use databinding your value is set at the time of databinding, however if you set it in the code-behind you can set it any stage of the pages lifecycle.

You may have some logic behind the value too and this is more readable/maintainable in the code-behind.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜