Unit 1
Unit 1
NET
ASP.NET is a web application framework designed and developed by Microsoft. ASP.NET is
open source and a subset of the .NET Framework and successor of the classic
ASP(Active Server Pages). With version 1.0 of the .NET Framework, it was first released in
January 2002. So a question comes to mind that which technology we were using before the
year 2002 for developing web applications and services? Answer is Classic ASP. So before
.NET and ASP.NET there was Classic ASP.
ASP.NET is built on the CLR(Common Language Runtime) which allows the programmers to
execute its code using any .NET language(C#, VB etc.). It is specially designed to work with
HTTP and for web developers to create dynamic web pages, web applications, web sites, and
web services as it provides a good integration of HTML, CSS, and JavaScript.
.NET Framework is used to create a variety of applications and services like Console, Web,
and Windows, etc. But ASP.NET is only used to create web applications and web services.
That’s why we termed ASP.NET as a subset of the .NET Framework.
ASP.NET History
ASP.NET evolved from traditional ASP. ASP stands for active server pages. Microsoft enhanced
this web technology and embedded it in its revolutionary .NET framework. Initially, two beta
releases of ASP.NET were released in 2000 and 2001. In the year 2002, Microsoft launched the
first version of its .NET framework, version 1.0 on the 5th of January 2002. ASP.NET 1.0 was
part of this framework. ASP.NET was built on Microsoft’s common language run time
technology which means that it can be used with any .NET language in a uniform manner.
Also, the ASP.NET SOAP extension framework makes it possible for ASP.NET components to
process SOAP messages.
Purpose
ASP.NET is a Microsoft scripting language created with the purpose of adding to the .NET
platform with tools and libraries specifically for building web apps and enabling developers to
create interactive websites. It also allows developers to use languages like Visual C#, Visual
Basic, Visual C++, and Visual F# to make websites.
ASP.NET expands the .NET platform by having a base framework for processing web requests
in C# or F# and with libraries for common web patterns, like the Model View Controller. It also
has editor extensions to code completion, syntax highlighting, and other functionality
specifically for developing web pages. For instance, Razor, a web page templating syntax is a
great tool for building dynamic web pages using C#.
Additionally, the authentication system included libraries, databases, and template pages for
handling logins, including multi-factor authentication and external authentication. ASP.NET has
another advantage in being cross-platform so it runs on macOS, Windows, Linux, and Docker.
ASP.NET Versions
Over the years, different versions and improvements in the .NET Framework have been made
these also included updates for ASP.NET. The most significant of these are considered in detail
chronologically.
This first version was released with Visual Studio .NET. It did more than simply rendering
HTML. In fact, it served the purpose of being an object-oriented Web application development
tool supporting other standard OOP features. So programmers were no longer forced to use
Server.CreateObject(…). Also, programmers could utilize DLL class libraries as well as other
features of the Web server to build more robust applications.
This version of the ASP.NET was released together with Visual Studio 2005 and Visual Web
Developer Express and the SQL Server 2005. It included upgrades that improved navigation
controls, master pages, and supported 64-bit processors. Other features introduced were login
controls, full pre-compilation, personalization services, new data controls, and a new technique
for declarative data access.
ASP.NET 3.0 (21 Nov 2006)
This version of the ASP.NET was released as an update with Windows Presentation Foundation
(WPF). The Windows Communication Foundation had the ability to use ASP.NET to host
services and Windows CardSpace used ASP.NET for login roles.
This version of the ASP.NET framework was released with Visual Studio 2008 Service Pack 1
with the capability to combine multiple JavaScript files into one file for more efficient
downloading, open new namespaces and with support for controlling browser history in an
ASP.NET AJAX application as well as the incorporation of ASP.NET Dynamic Data.
This version was released with parallel extensions and other .NET Framework 4 features. So the
main changes were new properties added in the Page class including the MetaKeyword and
MetaDescription.
This version of the ASO.NET framework was released with Visual Studio 2013 and included the
introduction of Open Web Interface for .NET which became a standard for an interface between
.NET Web applications and Web servers. Before these web applications could not easily be run
on another Web server unless with Mono because previous versions were built on top of IIS.
This version also had EF 6, MVC 5, and SignalR.
This is the current version of ASP.NET that is available. It has enhancements inaccessibility for
WinForms, service behavior for WCF, and High DPI. There are also JIT and NGEN
Improvements, updated ZLib, and reduced FIPS Impact on Cryptography.
ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set
a browser-to-server bilateral communication and cooperation.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes,
written using the extensible and reusable components or objects present in .Net framework.
These codes can use the entire hierarchy of classes in .Net framework.
The ASP.NET application codes can be written in any of the following languages:
C#
Visual Basic.Net
Jscript
J#
ASP.NET is used to produce interactive, data-driven web applications over the internet. It
consists of a large number of controls such as text boxes, buttons, and labels for assembling,
configuring, and manipulating code to create HTML pages.
ASP.NET web forms extend the event-driven model of interaction to the web applications. The
browser submits a web form to the web server and the server returns a full markup page or
HTML page in response.
All client side user activities are forwarded to the server for stateful processing. The server
processes the output of the client actions and triggers the reactions.
Now, HTTP is a stateless protocol. ASP.NET framework helps in storing the information
regarding the state of the application, which consists of:
Page state
Session state
The page state is the state of the client, i.e., the content of various input fields in the web form.
The session state is the collective information obtained from various pages the user visited and
worked with, i.e., the overall session state. To clear the concept, let us take an example of a
shopping cart.
User adds items to a shopping cart. Items are selected from a page, say the items page, and the
total collected items and price are shown on a different page, say the cart page. Only HTTP
cannot keep track of all the information coming from various pages. ASP.NET session state and
server side infrastructure keeps track of the information collected globally over a session.
The ASP.NET runtime carries the page state to and from the server across page requests while
generating ASP.NET runtime codes, and incorporates the state of the server side components in
hidden fields.
This way, the server becomes aware of the overall application state and operates in a two-tiered
connected way.
The ASP.NET component model provides various building blocks of ASP.NET pages.
Basically it is an object model, which describes:
Server side counterparts of almost all HTML elements or tags, such as <form> and
<input>.
Server controls, which help in developing complex user-interface. For example, the
Calendar control or the Gridview control.
ASP.NET is a technology, which works on the .Net framework that contains all web-related
functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.NET web
application is made of pages. When a user requests an ASP.NET page, the IIS delegates the
processing of the page to the ASP.NET runtime system.
The ASP.NET runtime transforms the .aspx page into an instance of a class, which inherits from
the base class page of the .Net framework. Therefore, each ASP.NET page is an object and all
its components i.e., the server-side controls are also objects.
It provides guidelines for declaring, using, and managing types at runtime, and
cross-language communication.
Metadata is the binary information describing the program, which is either stored
in a portable executable file (PE) or in the memory. Assembly is a logical unit
consisting of the assembly manifest, type metadata, IL code, and a set of
resources like image files.
(8) ADO.NET
It is the technology used for working with data and databases. It provides access
to data sources like SQL server, OLE DB, XML etc. The ADO.NET allows
connection to data sources for retrieving, manipulating, and updating data.
It provides a separation between the user interface and the business logic. It helps
in developing visually stunning interfaces using documents, media, two and three
dimensional graphics, animations, and more.
(11) Windows Communication Foundation (WCF)
It provides safety for accessing resources and sharing personal information on the
internet.
(13) LINQ
Feature of ASP.net
Microsoft has built a very powerful framework and most successful web application
development framework. Microsoft is delivering many new updates which are new and extended
features that help the developers to make their web application highly scalable. Also, which leads
to high performance. If we coupled both things that are application monitoring with other
performance tools like .net profiler tool (used to improve line by line code), it results in a more
powerful solution for building an unbelievable application.
To boost up and increase the performance of the application it has many great features that also
help to overcome the common development challenges. Web pages and technologies are created
with the help of ASP.NET.
Top Features of ASP.NET
Let’s see some major features of ASP.NET in detail so as to build a better application.
1. High Performance
Performance is always a critical feature for any of the applications or software. Due to its
ASP.NET Core and Kestrel web server, it’s remarked as the fastest and quick web application
framework which is available in the market. Due to its new Kestrel web server, it is more fast
and lightweight. Also, it has the advantage of asynchronous programming models. All other
things like python, java, jsp, php use an interpreter. However, compilers are faster as compared
to the interpreter. Compilers take all the code and compile at a time. So it is fast because
ASP.NET uses compiler-based technology.
2. Cross-Platform and Container Support
As we say it supports cross-platform means it supports Windows, macOS, and Linux. So if we
create ASP.NET application then we can directly deploy it on these platforms.
3. Asynchronous via Async/Await
Asynchronous programming patterns is now implemented in all .net frameworks classes and
3rd party libraries. You know why asp.net is faster, because of its wide use of asynchronous
patterns in kestrel frameworks. However, most of the applications spend their lots of time
waiting for database queries, web services call and its input-output operations to complete.
4. Rich Development Environments
If we are creating the application then we will use IDE i.e visual studio. It provides a rich
development environment by which we can easily drag and drop the components (radio buttons,
checkboxes, etc.) and create the application.
5. Language Independent
The framework is language independent that is developers can use various languages like C#. So
it’s easy for a developer to make its application by language which they know. We can create a
dynamic web application using any of the languages.
6. Supports for Web Sockets
Sockets are used to create a client – server-based Applications. By socket normally we can create
web-based client-server applications. These provide back and forth communication of the
browser.
7. Action Filters
NET supports a very great feature that is ACTION FILTERS. These filters are used to
implement error handling, authorization, caching or to any custom logic which we would like to
implement. There is a logic been implemented which will be executed before and after controller
action. To implement these logic Action filters are used.
8. Globalization and Localization
We host the web application and it can be accessed from anywhere globally. So language, date
and time format, number format, the currency must be different for different regions or countries.
ASP.NET supports globalization so that different countries’ clients or people also can understand
and they can access this application. ASP.NET customize our application for different languages
with the help of resource files. These files act as a central repository where all the texts are
placed.
9. Security
As it supports the .net framework so it will provide security for our application. Applications
have its individual identity, so before running this .net will check its identity of those objects. It
will also check the operating system security. Due to its pre-application configuration and feature
of built-in windows authentication, our developed application is safe and secure. With built-in
Windows authentication and per-application configuration, your applications are safe and
secured.
10. Supports for HTML5 Form Types
It provides support for HTML5 form types. There the new controls are available in HTML5 like
email, URL, Number, RNGE, Date pickers (week, date, month, time, DateTime-local, etc.),
color and search.
11. NET Web API
This includes ASP.NET web forms. HTTP services are easily consumed and build with the help
of ASP.NET Web API.
Why Should we Use ASP.NET?
Let see some of the important uses of ASP.NET which are given below:
We have seen so many features of ASP.NET and because of the wide variety of features and
functionalities, it is widely used in the market. Security is the major thing and the most important
one. Suppose we have logged in our bank account and then we navigated to the different
websites. If that other website does money transfer, it’s really a bad thing. So ASP.NET really
has a very good framework that will prevent these types of cyber-attacks.
Also, ASP.NET framework supports caching by which it’s easy to specify how long any request
should be cached through the common HTTP header.
ASP.NET is a server-side technology that uses compilers to compile the code which leads to
faster performance. Also, it reduces the number of lines of code to build large applications. One
of the major reasons for using ASP.NET is its wide variety of languages for building an
application. It is not restricted to only one language, it allows us to use .net languages like C#,
J#, VB, etc.
Many popular web sites like web amazon.com, eBay and many more use ASP.NET for its
development. webserver monitors and notices memory leaks, infinite loops, illegal activities. It
continuously monitors the web components and application pages. As soon as it found any of
these activities, it will destroy those activities there itself and restart.
ASP.NET pages are easy to write and maintain because of the source code and HTML codes are
together. As the source code is executed on the server-side it leads to powerful and flexible web
pages.
The Structure of an ASP.NET Page
You are now in a position to examine the formal structure of an ASP.NET page. The following is
a list of the important elements of an ASP.NET page:
Directives
Code declaration blocks
ASP.NET controls
Code render blocks
Server-side comments
Server-side include directives
Literal text and HTML tags
Directives
A directive controls how an ASP.NET page is compiled. The beginning of a directive is marked
with the characters <%@ and the end of a directive is marked with the characters %>. A
directive can appear anywhere within a page. By convention, however, a directive typically
appears at the top of an ASP.NET page.
There are several types of directives that you can add to an ASP.NET page. Two of the most
useful types are page and import directives.
Page Directives
You can use a page directive to specify the default programming language for a page. Page
directives can also be used to enable tracing and debugging for a page.
To change the default programming language of an ASP.NET page from Visual Basic to C#, for
example, you would use the following page directive:
NOTE
The keyword Page in a page directive is optional. The following two directives are equivalent:
Another extremely useful page directive is the Trace directive. If you enable tracing for a page,
additional information about the execution of the page is displayed along with the content of the
page (see Figure 5). You can enable tracing for a page by including the following directive:
After you enable tracing for a page, you can display trace messages by using two methods of
the Trace class: Write() and Warn(). You can use either method to display a custom message in
the trace information displayed at the bottom of the page. The only difference between the two
methods is that the former method displays messages in black text, and the latter method displays
messages in red text, which is easier to see.
Figure 5 Enabling page tracing.
The ASP.NET page in Listing 11 uses these methods to display various trace messages.
Listing 11—Trace.aspx
Sub Page_Load
Dim strTraceMessage As String
</Script>
<html>
<head><title>Trace.aspx</title></head>
<body>
</body>
</html>
To enable both tracing and debugging for a page, combine the directives like this (the order
of Debug and Trace is not important):
Import Directives
By default, only certain namespaces are automatically imported into an ASP.NET page. If you
want to refer to a class that isn't a member of one of the default namespaces, then you must
explicitly import the namespace of the class or you must use the fully qualified name of the class.
For example, suppose that you want to send an email from an ASP.NET page by using the Send
method of the SmtpMail class. The SmtpMail class is contained in
the System.Web.Mail namespace. This is not one of the default namespaces imported into an
ASP.NET page.
The easiest way to use the SmtpMail class is to add an Import directive to your ASP.NET page
to import the necessary namespace. The page in Listing 12 illustrates how to import
the System.Web.Mail namespace and send an email message.
Listing 12—ImportNamespace.aspx
<Script Runat="Server">
Sub Page_Load
Dim mailMessage As SmtpMail
mailMessage.Send( _
"[email protected]", _
"[email protected]", _
"Sending Mail!", _
"Hello!" )
End Sub
</Script>
<html>
<head><title>ImportNamespace.aspx</title></head>
<body>
<h2>Email Sent!</h2>
</body>
</html>
The first line in Listing 12 contains an import directive. Without the import directive, the page
would generate an error because it would not be able to resolve the SmtpMail class.
Instead of importing the System.Web.Mail namespace with the import directive, you could
alternatively use its fully qualified name. In that case, you would declare an instance of the class
like this:
In previous versions of ASP, you could declare a subroutine or function like this:
<%
Sub mySub
... subroutine code
End Sub
%>
Don't try this declaration with ASP.NET because it generates an error. You must use
the <Script> tag with ASP.NET like this:
<Script runat="Server">
Sub mySub
...subroutine code
End Sub
</Script>
The <Script Runat="Server"> tag accepts two optional attributes. First, you can specify the
programming language to use within the <Script> tag by including a language attribute like this:
In previous versions of Active Server Pages, you could include multiple languages in the same
page by using the language attribute with the <Script> tag. This technique doesn't work with
ASP.NET. You get an error if you attempt to use more than one language in the same page.
The second optional attribute of the <Script Runat="Server"> tag is SRC. You can use it to
specify an external file that contains the contents of the code block. This is illustrated in Listings
13 and 14.
Listing 13—ExternalFile.aspx
<html>
<head><title>ExternalFile.aspx</title></head>
<body>
<form Runat="Server">
<asp:Button
Text="Click Here!"
OnClick="Button_Click"
Runat="Server"/>
</form>
</body>
</html>
Listing 14—ApplicationLogic.aspx
The page in Listing 13, ExternalFile.aspx, uses the SRC attribute to include the code in Listing
14, ApplicationLogic.aspx.
ASP.NET Controls
ASP.NET controls can be freely interspersed with the text and HTML content of a page. The
only requirement is that the controls should appear within a <form Runat="Server"> tag. And,
for certain tags such as <span Runat="Server"> and <ASP:Label Runat="Server"/>, this
requirement can be ignored without any dire consequences.
One significant limitation of ASP.NET pages is that they can contain only one <form
Runat="Server"> tag. This means that you cannot group ASP.NET into multiple forms on a
page. If you try, you get an error.
Code Render Blocks
If you need to execute code within the HTML or text content of your ASP.NET page, you can do
so within code render blocks. The two types of code render blocks are inline code and inline
expressions. Inline code executes a statement or series of statements. This type of code begins
with the characters <% and ends with the characters %>.
Inline expressions, on the other hand, display the value of a variable or method (this type of code
is shorthand for Response.Write). Inline expressions begin with the characters <%= and end with
the characters %>.
The ASP.NET page in Listing 15 illustrates how to use both inline code and inline expressions in
an ASP.NET page.
Listing 15—CodeRender.aspx
<Script Runat="Server">
Dim strSomeText As String
Sub Page_Load
strSomeText = "Hello!"
End Sub
</Script>
<html>
<head><title>CodeRender.aspx</title></head>
<body>
<form Runat="Server">
<p>
</form>
</body>
</html>
Notice that you can use variables declared in the code declaration block within the code render
block. However, the variable has to be declared with page scope. The variable could not, for
example, be declared within the Page_Load subroutine.
Server-side Comments
You can add comments to your ASP.NET pages by using server-side comment blocks. The
beginning of a server-side comment is marked with the characters <%-- and the end of the
comment is marked with the characters --%>.
Server-side comments can be added to a page for the purposes of documentation. Note that you
cannot see the contents of server-side comment tags, unlike normal HTML comment tags, by
using the View Source command on your Web browser.
Server-side comments can also be useful when you're debugging an ASP.NET page. You can
temporarily remove both ASP.NET controls and code render blocks from a page by surrounding
these elements with server-side comments. The page in Listing 16 illustrates this use.
Listing 16—ServerComments.aspx
<Script Runat="Server">
Dim strSomeText As String
Sub Page_Load
strSomeText = "Hello!"
End Sub
</Script>
<html>
<head><title>ServerComments.aspx</title></head>
<body>
<form Runat="Server">
<%--
This is inside the comments
<asp:Label Text="hello!" Runat="Server" />
<%= strSomeText %>
--%>
</form>
</body>
</html>
Alternatively, you can include a file by supplying the full virtual path. For example, if you have a
subdirectory named myDirectory under the wwwroot directory, you can include a file from that
directory like this:
The include directive is executed before any of the code in a page. One implication is that you
cannot use variables to specify the path to the file that you want to include. For example, the
following directive would generate an error:
TIP
Instead of working with include directives, consider working with user controls instead. User
controls provide you with more flexibility. For example, you can create custom properties and
methods with a user control.
Literal Text and HTML Tags
The final type of element that you can include in an ASP.NET page is HTML content. The static
portion of your page is built with plain old HTML tags and text.
You might be surprised to discover that the HTML content in your ASP.NET page is compiled
along with the rest of the elements. HTML content in a page is represented with
the LiteralControl class. You can use the Text property of the LiteralControl class to manipulate
the pure HTML portion of an ASP.NET page.
The HTML content contained in the page in Listing 17, for example, is reversed when it is
displayed (see Figure 6). The Page_Load subroutine walks through all the controls in a page
(including the LiteralControl) and reverses the value of the Text property of each control.
Listing 17—Literal.aspx
<Script Runat="Server">
Sub Page_Load
Dim litControl As LiteralControl
</Script>
<html>
<head><title>Literal.aspx</title></head>
<body>
<b>This text is reversed</b>
</body>
</html>
ASP.NET comes in three types: MVC, Web Forms and Web Pages.
Web Forms – This is the classic ASP.NET framework; it has all the server side controls and is
used for creating dynamic websites. It does have a steep learning curve and controls most of the
mark-up so there is little control. It is event-driven and is good for RAD (Rapid Application
Development).
MVC – Model-View-Controller, this framework also has a steep learning curve, however, it is
ideal for developers who like to have control over their websites and like to separate logic and
UI. It is ideal for team based work.
Web Pages – This is the easiest of all and is what you’ll be learning. It uses the Razor View
Engine and is easy to learn providing you have a good understanding of HTML, CSS, JavaScript
and either C# or Visual Basic
ASP.NET - Single-Page Applications: Build Modern, Responsive Web Apps with ASP.NET
By Mike Wasson
Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically
update that page as the user interacts with the app.
SPAs use AJAX and HTML5 to create fluid and responsive Web apps, without constant page
reloads. However, this means much of the work happens on the client side, in JavaScript. For the
traditional ASP.NET developer, it can be difficult to make the leap. Luckily, there are many
open source JavaScript frameworks that make it easier to create SPAs.
In this article, I’ll walk through creating a simple SPA app. Along the way, I’ll introduce some
fundamental concepts for building SPAs, including the Model-View-Controller (MVC) and
Model-View-ViewModel (MVVM) patterns, data binding and routing.
The sample app I created is a simple movie database, shown in Figure 1. The far-left column of
the page displays a list of genres. Clicking on a genre brings up a list of movies within that
genre. Clicking the Edit button next to an entry lets you change that entry. After making edits,
you can click Save to submit the update to the server, or Cancel to revert the changes.
I created two different versions of the app, one using the Knockout.js library and the other using
the Ember.js library. These two libraries have different approaches, so it’s instructive to compare
them. In both cases, the client app was fewer than 150 lines of JavaScript. On the server side, I
used ASP.NET Web API to serve JSON to the client. You can find source code for both versions
of the app at github.com/MikeWasson/MoviesSPA.
(Note: I created the app using the release candidate [RC] version of Visual Studio 2013. Some
things might change for the released to manufacturing [RTM] version, but they shouldn’t affect
the code.)
Background
In a traditional Web app, every time the app calls the server, the server renders a new HTML
page. This triggers a page refresh in the browser. If you’ve ever written a Web Forms application
or PHP application, this page lifecycle should look familiar.
In an SPA, after the first page loads, all interaction with the server happens through AJAX calls.
These AJAX calls return data—not markup—usually in JSON format. The app uses the JSON
data to update the page dynamically, without reloading the page. Figure 2 illustrates the
difference between the two approaches.
One benefit of SPAs is obvious: Applications are more fluid and responsive, without the jarring
effect of reloading and re-rendering the page. Another benefit might be less obvious and it
concerns how you architect a Web app. Sending the app data as JSON creates a separation
between the presentation (HTML markup) and application logic (AJAX requests plus JSON
responses).
This separation makes it easier to design and evolve each layer. In a well-architected SPA, you
can change the HTML markup without touching the code that implements the application logic
(at least, that’s the ideal). You’ll see this in action when I discuss data binding later.
In a pure SPA, all UI interaction occurs on the client side, through JavaScript and CSS. After the
initial page load, the server acts purely as a service layer. The client just needs to know what
HTTP requests to send. It doesn’t care how the server implements things on the back end.
With this architecture, the client and the service are independent. You could replace the entire
back end that runs the service, and as long as you don’t change the API, you won’t break the
client. The reverse is also true—you can replace the entire client app without changing the
service layer. For example, you might write a native mobile client that consumes the service.
Visual Studio 2013 has a single ASP.NET Web Application project type. The project wizard lets
you select the ASP.NET components to include in your project. I started with the Empty
template and then added ASP.NET Web API to the project by checking Web API under “Add
folders and core references for:” as shown in Figure 3.
The new project has all the libraries needed for Web API, plus some Web API configuration
code. I didn’t take any dependency on Web Forms or ASP.NET MVC.
Notice in Figure 3 that Visual Studio 2013 includes a Single Page Application template. This
template installs a skeleton SPA built on Knockout.js. It supports log in using a membership
database or external authentication provider. I didn’t use the template in my app because I
wanted to show a simpler example starting from scratch. The SPA template is a great resource,
though, especially if you want to add authentication to your app.
I used ASP.NET Web API to create a simple REST API for the app. I won’t go into detail about
Web API here—you can read more at asp.net/web-api.
First, I created a Movie class that represents a movie. This class does two things:
Tells Entity Framework (EF) how to create the database tables to store the movie data.
Tells Web API how to format the JSON payload.
You don’t have to use the same model for both. For example, you might want your database
schema to look different from your JSON payloads. For this app, I kept things simple:
Copy
namespace MoviesSPA.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public int Year { get; set; }
public string Genre { get; set; }
public string Rating { get; set; }
}
}
Next, I used Visual Studio scaffolding to create a Web API controller that uses EF as the data
layer. To use the scaffolding, right-click the Controllers folder in Solution Explorer and select
Add | New Scaffolded Item. In the Add Scaffold wizard, select “Web API 2 Controller with
actions, using Entity Framework,” as shown in Figure 4.
Figure 4 Adding a Web API Controller
Figure 5 shows the Add Controller wizard. I named the controller MoviesController. The name
matters, because the URIs for the REST API are based on the controller name. I also checked
“Use async controller actions” to take advantage of the new async feature in EF 6. I selected the
Movie class for the model and selected “New data context” to create a new EF data context.
MoviesController.cs defines the Web API controller that implements the REST API for the
app.
MovieSPAContext.cs is basically EF glue that provides methods to query the underlying
database.
Figure 6 shows the default REST API the scaffolding creates.
Figure 6 The Default REST API Created by the Web API Scaffolding
T AB LE 1
Values in curly brackets are placeholders. For example, to get a movie with ID equal to 5, the
URI is /api/movies/5.
I extended this API by adding a method that finds all the movies in a specified genre:
XMLCopy
The client puts the genre in the query string of the URI. For example, to get all movies in the
Drama genre, the client sends a GET request to /api/movies?genre=drama. Web API
automatically binds the query parameter to the genre parameter in the GetMoviesByGenre
method.
So far, I’ve just created a REST API. If you send a GET request to /api/movies?genre=drama,
the raw HTTP response looks like this:
XMLCopy
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Date: Tue, 10 Sep 2013 15:20:59 GMT
Content-Length: 240
[{"ID":5,"Title":"Forgotten Doors","Year":2009,"Genre":"Drama","Rating":"R"},
{"ID":6,"Title":"Blue Moon June","Year":1998,"Genre":"Drama","Rating":"PG-
13"},{"ID":7,"Title":"The Edge of the Sun","Year":1977,"Genre":"Drama","Rating":"PG-13"}]
Now I need to write a client app that does something meaningful with this. The basic workflow
is:
You could code all of this by hand. For example, here’s some jQuery code that creates a list of
movie titles:
Copy
$.getJSON(url)
.done(function (data) {
// On success, "data" contains a list of movies
var ul = $("<ul></ul>")
$.each(data, function (key, item) {
// Add a list item
$('<li>', { text: item.Title }).appendTo(ul);
});
$('#movies').html(ul);
});
This code has some problems. It mixes application logic with presentation logic, and it’s tightly
bound to your HTML. Also, it’s tedious to write. Instead of focusing on your app, you spend
your time writing event handlers and code to manipulate the DOM.
The solution is to build on top of a JavaScript framework. Luckily, you can choose from many
open source JavaScript frameworks. Some of the more popular ones include Backbone, Angular,
Ember, Knockout, Dojo and JavaScriptMVC. Most use some variation of the MVC or MVVM
patterns, so it might be helpful to review those patterns.
A more recent variant of MVC is the MVVM pattern (see Figure 8). In MVVM:
In a JavaScript MVVM framework, the view is markup and the view model is code.
MVC has many variants, and the literature on MVC is often confusing and contradictory.
Perhaps that’s not surprising for a design pattern that started with Smalltalk-76 and is still being
used in modern Web apps. So even though it’s good to know the theory, the main thing is to
understand the particular MVC framework you’re using.
For the first version of my app, I used the Knockout.js library. Knockout follows the MVVM
pattern, using data binding to connect the view with the view model.
To create data bindings, you add a special data-binding attribute to the HTML elements. For
example, the following markup binds the span element to a property named genre on the view
model. Whenever the value of genre changes, Knockout automatically updates the HTML:
XMLCopy
<h1><span data-bind="text: genre"></span></h1>
Bindings can also work in the other direction—for example, if the user enters text into a text box,
Knockout updates the corresponding property in the view model.
The nice part is that data binding is declarative. You don’t have to wire up the view model to the
HTML page elements. Just add the data-binding attribute and Knockout does the rest.
(Note: I used the Bootstrap library to style the app, so the real app has a lot of extra <div>
elements and CSS classes to control the formatting. I left these out of the code examples for
clarity.)
XMLCopy
<!DOCTYPE html>
<html>
<head>
<title>Movies SPA</title>
</head>
<body>
<ul>
<li><a href="#"><!-- Genre --></a></li>
</ul>
<table>
<thead>
<tr><th>Title</th><th>Year</th><th>Rating</th>
</tr>
</thead>
<tbody>
<tr>
<td><!-- Title --></td>
<td><!-- Year --></td>
<td><!-- Rating --></td></tr>
</tbody>
</table>
<p><!-- Error message --></p>
<p>No records found.</p>
</body>
</html>