Reputation: 1253
I'm cleaning up some older C# code and I ran across this block in the Page_Load
method.
txtFirstName.Attributes.Add("onchange", "CheckChange();");
txtMiddleName.Attributes.Add("onchange", "CheckChange();");
txtLastName.Attributes.Add("onchange", "CheckChange();");
txtIdentifier.Attributes.Add("onchange", "CheckChange();");
Would it be more efficient to leave it as it is, or set those particular attributes in the HTML?
Upvotes: 3
Views: 381
Reputation: 66641
I create a simple page with this TextBox
<asp:TextBox runat="server" ID="txtFirstName" onblur="CheckBlur()"></asp:TextBox>
and on PageLoad I place that line
txtFirstName.Attributes.Add("onchange", "CheckChange();");
Now, I go and check the compiled files and found that the compiler add this line
#line 12 "D:\StackOverFlow\AttrTest.aspx"
((System.Web.UI.IAttributeAccessor)(@__ctrl)).SetAttribute("onblur", "CheckBlur()");
so, the compiler add the same line the same way you place it on code behind. So from that point of view the results seems to be the same in a manner of speed, or compile of the page.
Upvotes: 3
Reputation: 4809
I'd rather prefer writing in aspx page, and will choose code-behind in situations where its not possible to do so like generating anchor dynamically after page is submitted and linking some javascript to it. It comes to maintainability rather than performance.
Edit
As an additional input, consider having loosely coupled code in javascript instead of directly specifying events on tags like
document.getElementById('txtLastName').onclick = function () {
//code
};
Upvotes: 1
Reputation: 150293
Would it be more efficient to leave it as it is, or set those particular attributes in the HTML?
I think efficiency here is a lot less important and probably the difference will be extremely small either way.
But... I think HTML attributes and specially javascript events and code should be written on the client side.
Separate of concerns when you write the client code on the client side your code is a lot easier to develop and maintain. This is one of the reasons Asp.net-MVC is being used in new applications while Asp.Net has almost 0 new applications.
Upvotes: 4
Reputation: 8860
I suppose it would be slightly more efficient to set them in HTML, because HTML can be written to output as-is and the object-model of control needs to be converted to HTML using some string concatenation and formatting operations.
But all in all I suppose that wouldn't affect the performance of your page if you don't have thousands of such attributes.
Though, I'm not 100% sure because I never tried such micro-optimizations
Upvotes: 1