Skip to main content



Beginning ASP.NET 4: in C# and VB

Imar Spaanjaars

ISBN: 978-0-470-50221-1 March 2010 840 Pages


This book is for anyone who wants to learn how to build rich and interactive web sites that run on the Microsoft platform. With the knowledge you gain from this book, you create a great foundation to build any type of web site, ranging from simple hobby-related web sites to sites you may be creating for commercial purposes.

Anyone new to web programming should be able to follow along because no prior background in web development is assumed although it helps if you do have a basic understanding of HTML and the web in general. The book starts at the very beginning of web development by showing you how to obtain and install Visual Web Developer. The chapters that follow gradually introduce you to new technologies, building on top of the knowledge gained in the previous chapters.

Do you have a strong preference for Visual Basic over C# or the other way around? Or do you think both languages are equally cool? Or maybe you haven't made up your mind yet and want to learn both languages? Either way, you'll like this book because all code examples are presented in both languages!

Even if you have some experience with prior versions of ASP.NET, you may gain a lot from this book. Although many concepts from previous versions are brought forward into ASP.NET 4, you'll discover there's a lot of new stuff to be found in this book, including an introduction to the ADO.NET Entity Framework, the inclusion of jQuery, ASP.NET AJAX, the many changes to the ASP.NET 4 Framework, and much more.

This book teaches you how to create a feature-rich, data-driven, and interactive web site called Planet Wrox. Although this is quite a mouthful, you'll find that with Visual Web Developer 2010, developing such a web site isn't as hard as it seems. You'll see the entire process of building a web site, from installing Visual Web Developer 2010 in Chapter 1 all the way up to putting your web application on a live server in Chapter 19. The book is divided into 19 chapters, each dealing with a specific subject.

  • Chapter 1, “Getting Started with ASP.NET 4” shows you how to obtain and install Visual Web Developer 2010. You'll get instructions for downloading and installing the free edition of Visual Web Developer 2010, called the Express edition. You are also introduced to HTML, the language behind every web page. The chapter closes with an overview of the customization options that Visual Web Developer gives you.

  • Chapter 2, “Building an ASP.NET Web Site” shows you how to create a new web site and how to add new elements like pages to it. Besides learning how to create a well-structured site, you also see how to use the numerous tools in Visual Web Developer to create HTML and ASP.NET pages.

  • Chapter 3, “Designing Your Web Pages.” Visual Web Developer comes with a host of tools that allow you to create well-designed and attractive web pages. In this chapter, you see how to make good use of these tools. Additionally, you learn about CSS, the language that is used to format web pages.

  • Chapter 4, “Working with ASP.NET Server Controls.” ASP.NET Server Controls are one of the most important concepts in ASP.NET. They allow you to create complex and feature-rich web sites with very little code. This chapter introduces you to the large number of server controls that are available, explains what they are used for, and shows you how to use them.

  • Chapter 5, “Programming Your ASP.NET Web Pages.” Although the built-in CSS tools and the ASP.NET Server Controls can get you a long way in creating web pages, you are likely to use a programming language to enhance your pages. This chapter serves as an introduction to programming with a strong focus on programming web pages. Best of all: all the examples you see in this chapter (and the rest of the book) are in both Visual Basic and C#, so you can choose the language you like best.

  • Chapter 6, “Creating Consistent Looking Web Sites.” ASP.NET helps you create consistent-looking pages through the use of master pages, which allow you to define the global look and feel of a page. Skins and themes help you to centralize the looks of controls and other visual elements in your site. You also see how to create a base page that helps to centralize programming code that you need on all pages in your site.

  • Chapter 7, “Navigation.” To help your visitors find their way around your site, ASP.NET comes with a number of navigation controls. These controls are used to build the navigation structure of your site. They can be connected to your site's central site map that defines the pages in your web site. You also learn how to programmatically send users from one page to another.

  • Chapter 8, “User Controls.” User controls are reusable page fragments that can be used in multiple web pages. As such, they are great for repeating content such as menus, banners, and so on. In this chapter, you learn how to create and use user controls and enhance them with some programmatic intelligence.

  • Chapter 9, “Validating User Input.” A large part of interactivity in your site is defined by the input of your users. This chapter shows you how to accept, validate, and process user input using ASP.NET Server Controls. Additionally, you see how to send e-mail from your ASP.NET web application and how to read from text files.

  • Chapter 10, “ASP.NET AJAX.” Microsoft ASP.NET AJAX allows you to create good-looking, flicker-free web pages that close the gap between traditional desktop applications and web applications. In this chapter you learn how to use the built-in Ajax features to enhance the presence of your web pages, resulting in a smoother interaction with the web site.

  • Chapter 11, “jQuery.” jQuery is a popular, open source and cross-browser JavaScript library designed to make it easier to interact with web pages in the client’s browser. In this chapter you learn the basics of jQuery and see how to add rich visual effects and animations to your web pages.

  • Chapter 12, “Introducing Databases.” Understanding how to use a database is critical to building web sites, as most modern web sites require the use of a database. You’ll learn the basics of SQL, the query language that allows you to access and alter data in a database. In addition, you are introduced to the database tools found in Visual Web Developer that help you create and manage your SQL Server databases.

  • Chapter 13, “Displaying and Updating Data.” Building on the knowledge you gained in the previous chapter, this chapter shows you how to use the ASP.NET data-bound and data source controls to create a rich interface that enables your users to interact with the data in the database that these controls target.

  • Chapter 14, “LINQ and the ADO.NET Entity Framework.” LINQ is Microsoft’s solution for accessing objects, databases, XML, and more. The ADO.NET Entity Framework (EF) is Microsoft's new technology for database access. This chapter shows you what LINQ is all about, how to use the visual EF designer built into Visual Studio, and how to write LINQ to EF queries to get data in and out of your SQL Server database.

  • Chapter 15, “Working with Data—Advanced Topics.” While earlier chapters focused mostly on the technical foundations of working with data, this chapter looks at the same topic from a front-end perspective. You see how to change the visual appearance of your data through the use of control styles. You also see how to interact with the data-bound controls and how to speed up your application by keeping a local copy of frequently accessed data.

  • Chapter 16, “Security in Your ASP.NET 4 Web Site.” Although presented quite late in the book, security is a first-class, important topic. This chapter shows you how to make use of the built-in ASP.NET features related to security. You learn about a number of application services that facilitate security. You also learn how to let users sign up for an account on your web site, how to distinguish between anonymous and logged-on users, and how to manage the users in your system.

  • Chapter 17, “Personalizing Web Sites.” Building on the security features introduced in Chapter 16, this chapter shows you how to create personalized web pages with content targeted at individual users. You see how to configure and use ASP.NET Profile that enables you to store personalized data for known and anonymous visitors.

  • Chapter 18, “Exception Handling, Debugging, and Tracing.” In order to understand, improve, and fix the code you write for your ASP.NET web pages you need good debugging tools. Visual Web Developer ships with great debugging support that enables you to diagnose the state of your application at run time, helping you find and fix problems before your users do.

  • Chapter 19, “Deploying Your Web Site.” By the end of the book, you should have a web site that is ready to be shown to the world. But how exactly do you do that? What are the things you need to know and understand to put your web site out in the wild? This chapter gives the answers and provides you with a good look at configuring different production systems in order to run your final web site.

Related Resources

Buy Both and Save 25%!

This item: Beginning ASP.NET 4: in C# and VB

Professional ASP.NET Design Patterns (Paperback £37.99)

Cannot be combined with any other offers.

Original Price:£72.98

Purchased together:£54.74

save £18.24


Foreword xxv

Introduction xxvii

Getting Chapter 1: Started with AS P.NET 4 1

Chapter 2: Building an AS P.NET Web Site 33

Chapter 3: Designing Your Web Pages 65

Chapter 4: Working with AS P.NET Server Controls 105

Chapter 5: Programming Your AS P.NET Web Pages 139

Chapter 6: Creating Consistent Looking Web Sites 197

Chapter 7: Navigation 239

Chapter 8: User Controls 271

Chapter 9: Validating User Input 297

Chapter 10: AS P.NET AJAX 331

Chapter 11: jQuery 367

Chapter 12: Introducing Databases 403

Chapter 13: Displaying and Updating Data 433

Chapter 14: LIN Q and the ADO .NET Entity Framework 477

Chapter 15: Working with Data — Advanced Topics 529

Chapter 16: Security in Your AS P.NET 4 Web Site 579

Chapter 17: Personalizing Web Sites 619

Chapter 18: Exception Handling, Debugging, and Tracing 655

Chapter 19: Deploying Your Web Site 697

Appendix A: Exercise Answers 731

Appendix B: Configuring SQL Server 2008 757

Index 777

Code Download - C#
Code Download - VB
ChapterPageDetailsDatePrint Run
Service Pack 1
Service Pack 1 for Visual Web Developer 2010 Express and Visual Studio 2010 introduces a change in the way the Visual Basic editor writes methods for you in the Code Behind of your pages. The editor no longer adds the ByVal keyword to new methods it creates. Since ByVal was already the default for method parameters, this change doesn't affect your code. Whenever you see ByVal used in the book, you can choose to type the code as shown in the book, or you can leave out the ByVal keyword as VWD 2010 / VS 2010 do when writing new methods.

For a detailed explanation of the issue, check out this forum post:

xxxvTypo in Text
If you want to following along...

Should be:

If you want to follow along...

16Error in Text
Under "The Main Menu," currently reads:
"Offline helps..."

Should read:
"Offline help..."

34Error in Text
Under "Creating Web Sites with VWD 2010," currently reads:
"...create different kind of sites..."

Should read:
"...create different kinds of sites"

238Error in Text
Chapter 2, page 38, step 5, second sentence should read:

The other two options (HTTP and FTP) enable you to open a site running on IIS (either on your local machine, or on a remote server using the so-called Microsoft FrontPage Server Extensions) and open a site from an FTP server, respectively.

44Error in Code
The table says that the file extension for the FileType Entity Data Model is .dbml instead of .edmx

71Error in Text
In Figure 3-2:


Should be:


With curly brackets instead of parentheses

119Error in Text
At the top of the page it reads "that they enables you" but it should be "that they enable you."


5148Insert Text
after the last code block that shows how the use the Resize method, the following text should be inserted:

Because the compiler can determine the type of each element in the roles array, you don't have to explicitly specify the type in angled brackets. The following line of code would work equally well:

Array.Resize(ref roles, 3);

Under the hood, the compiler figures out the type (a string) and then actually calls Array.Resize(ref roles, 3).

169Improved VB.NET Example
While the first VB code example runs fine as it is, it would align better with the C# example if AndAlso was used instead of And (since the C# example uses && instead of &). So the new example would read as follows:

Dim success As Boolean = False
Dim loopCount As Integer = 0
While Not success AndAlso loopCount < 3
success = SendEmailMessage()
loopCount = loopCount + 1
End While

Page 158 discusses the AndAlso and && operators.

209Errors in text
the text:
Also during this phase, the control properties are loaded from View State and Control State again during a postback. So, for example, when you change the selected item in a DropDownList and then cause a postback, this is the moment where the correct item gets preselected in the drop-down list again, which you can then work with in your server-side code.

should be in the cell for the Load section, not for the Page initialization section. Therefore, the text under 'Page initialization' should read:

During this phase, the controls you have set up in your page or added programmatically become available. Additionally, the Page class fires three events: Init, InitComplete, and PreLoad.

And the text under load should read:

During this phase the page raises the Load event. Also during this phase, the control properties are loaded from View State and Control State again during a postback. So, for example, when you change the selected item in a DropDownList and then cause a postback, this is the moment where the correct item gets preselected in the drop-down list again, which you can then work with in your server-side code.

220Error in Text
Page 220, in the paragraph above Figure 6-13, it reads "whose settings can be overridden by the individual pages". This should be: "whose settings can be overridden by the individual controls"

232Error in Text
third paragraph, or just after
Page.Theme = preferredTheme.Value;
this sentence should be rephrased:
"Because the theme is set early . . . to the end of the page, . . ."

Should say:
"Because the theme is set early in the page's life cycle, this setting is applied throughout the page, effectively giving the page the look and feel defined in it."

263Error in Text
Second Paragraph in Programmatic Redirection.

Says: "The third option, Server.Transfer, executes at the client."

Should be: " the server" not client.

279Error in Text
In the Try it out Section (Registering User Controls in the web.config File). The 2nd sentence next to bullet point 1 reads: "If you're familiar with previous versions of ASP.NET you may find the web.config worrying empty". This should read "worryingly empty".

8285Error in Reference
Step 5 of the Try It Out:
The paragraph references the src attribute twice. In both cases, this should be ImageUrl instead.

291Change in Text
"by pressing F5" can be changed to "by pressing Control (Ctl) F5"

Ctrl+F5 is what we've been using up to this point. Just using F5 will work equally well, so is not really an error, but it starts the website in Debug mode. Debugging is not covered until Chapter 18.

6312Error in Text
After the script addition, the paragraph begins with:

"If you find that VDW"

It should be:



9316Error in Code
Chapter 9, page 316 Under the heading "Understanding Request Validation" you see a way to turn off request validation using the ValidateRequest attribute on the page. However, in order for this to work, you also need to configure your application to use Request Validation the way it did in earlier versions of the .NET Framework. To do this, you need to add or update the <httpRuntime /> element in the web.config as follows:

<httpRuntime requestValidationMode="2.0" />

This puts validation in a 2.0 compatible mode, which makes Request Validation work as expected.

344Error in Note
in the Note section. The text currently reads:
"you can temporarily remove the UpdatePanel from the page, or uncomment its closing and opening tags"

but should read:
"you can temporarily remove the UpdatePanel from the page, or comment out its closing and opening tags"

368Error in Text
The text in the book is:

"Initially developed and released by John Resig in January 2006, jQuery has grown to be a very popular client-side frameworks."

Which should be:

"Initially developed and released by John Resig in January 2006, jQuery has grown to be a very popular client-side framework."

377Error in Text
In the "Try It Out" Using Basic Selectors Number 4, it reads:

"...Design View, locate the cpClientScipt placeholder..."

Should be:

"...Design View, locate the cpClientScript placeholder..."

397Error in Text
Try It Out: Step 4, fourth sentence:

should be:
"CssClass" (with 2 s's instead of 3)

436Error in Text
first sentence of the last paragraph currently reads:
"...the next Try It Out shows you how to you create a very simple data-driven web page"

but should read:
"...the next Try It Out shows you how to create a very simple data-driven web page"

439Error in Text
Right below Figure 13-5.

Text reads, "If the list with reviews ends up..."

Should read, "If the list with genres ends up..."

495Error in Text
Third paragraph, the third sentence begins "Using Eval you can get the value of the Title and assign it to the Literal, ..."

Should read "Using Eval you can get the value of the genre Name and assign it to the Literal, ..."

533Error in Code
The table lists the ASP.Net style RowStyle as the necessary style needed to change the Header of the GridView. This should be HeaderStyle.

574Error in Text
In the paragraph below the code example showing the Cache.Insert method the text should read as follows:
The first parameter of the Insert method is the cache key and the second parameter is the object you want to cache: the actual Review instance in this case. The third parameter enables you to hook up your cached item to some dependency such as a file or a database so the item is removed from the cache when the dependent object changes. This is not used in this example, so null (Nothing in VB) is passed. The fourth parameter defines the absolute expiration date: the date and time at which the item is considered outdated and has to be removed from the cache. In this example this date".. (text continues as printed here)

617Error in Text
Second paragraph in summary:

In general, authentication encompasses three important concepts: identity, authentication, and authorization. Together, they determine who you are and what you are allowed to do.

The first "authentication" should be "security". This makes the paragraph:

In general, security encompasses three important concepts: identity, authentication, and authorization. Together, they determine who you are and what you are allowed to do.

631Error in Text
The second to last paragraph reads "With the tricks you learned in Chapter 15 you make the controls even more accessible by setting the AccessKey properties.".

This sentence should read "With the tricks you learned in Chapter 15 you could make the controls even more accessible by setting the AccessKey properties."

18669Error in Code
step 10: The code reads:
<h1>Un unknown error occurred</h1>

But should read:
<h1>An unknown error occurred</h1>

11/Appendix A743 Error in Code
There's an error in the jQuery code for the answer to question 1 of Chapter 11. Replace the code block that follows the text "In a script block below the last panel you need to add the following code:" with the following code:

$(function ()
  $('#HideBanner').bind('click', function ()
    $('#VerticalPanel').slideToggle('fast', function ()
      if ($(this).css('display') == 'block')
        $('#HideBanner').text('Hide Banner');
        $('#HideBanner').text('Show Banner');
This code specifies a callback argument to slideToggle to run some code when slideToggle is ready. Inside the block that is executed, the display setting is checked, and the text of the link is updated accordingly. Notice how the code is now wrapped in function () { ... } so it's called when slideToggle is done.

8Error in Chapter 8 Figure
In the images of the Solution Explorer, file name currently reads: 468

Should read: 486

6Error in Code
In the Try Out in Chapter 6, the code currently reads:

Currently reads (with curly quotes):

Should read (with straight quotes):

15557 and 560Text Correction
figure 15-14 is incorrect.
in the figure, the first letter of Summary (S) is underlined which does not match page 557, step number three, where the code indicates the 2nd letter (u) should be underlined. The code is correct, the figure is incorrect.