Using a Code-Behind File

Code blocks are great for simple tasks and are especially well-suited to setting values for HTML element attributes, as we did for the img element in the previous section. Their main drawback is that they are harder to read and maintain than regular C# files, because the code statements are dispersed throughout the page and mingled in with the HTML.

A common use for code blocks is to insert values into JavaScript files, so that we can refer to elements in an ASP.NET web page. You will see how this is done, and understand why it is required, in Chapter 9. For more complex pages, a more useful (and commonly used) approach is to separate the HTML and directives into one file and the C# code into another. When you do this, ...

Get Applied ASP.NET 4 in Context now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.