0% found this document useful (0 votes)
61 views

A Blog Post: Mytable

The document provides an introduction and overview of jQuery, including: - jQuery is a lightweight JavaScript library that allows efficient DOM manipulation with minimal code. - It uses CSS selectors and methods chained together via the $ symbol. - Common tasks include selecting elements, adding/modifying content, and handling events. - ASP.NET officially includes jQuery in Visual Studio to simplify AJAX and client-side development. - The document discusses how to consume ASP.NET web services using jQuery's AJAX methods.

Uploaded by

prashantkhapre
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

A Blog Post: Mytable

The document provides an introduction and overview of jQuery, including: - jQuery is a lightweight JavaScript library that allows efficient DOM manipulation with minimal code. - It uses CSS selectors and methods chained together via the $ symbol. - Common tasks include selecting elements, adding/modifying content, and handling events. - ASP.NET officially includes jQuery in Visual Studio to simplify AJAX and client-side development. - The document discusses how to consume ASP.NET web services using jQuery's AJAX methods.

Uploaded by

prashantkhapre
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

Introduction

In September 2008 Scott Guthrie, the head of the ASP.NET team, announced in a blog
post that Visual Studio would be shipping with the jQuery library. He writes:

“jQuery is a lightweight open source JavaScript library (only 15kb in size) that in a
relatively short span of time has become one of the most popular libraries on the web. A
big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and
manipulate HTML elements with minimum lines of code … There is a huge ecosystem and
community built up around JQuery. The jQuery library also works well on the same page
with ASP.NET AJAX and the ASP.NET AJAX Control Toolkit.”

With that, JQuery is officially embraced by ASP.NET.

A brief introduction of JQuery

jQuery is the star among the growing list of JavaScript libraries. A few of its
characteristics are light-weight, cross-browser compatibility and simplicity. A common
task that sometimes takes 10 lines of code with traditional JavaScript can be
accomplished with jQuery in just one line of code. For example, if you want to dress up a
table with an ID mytable with alternative color for every other row, you can simple do
this in jQuery.

Listing 1: jQuery code for making a zebra-style table


<script>
$(function() {
$("table#mytable tr:nth
});
</script>

The magic dollar sign ($) and a chain of operations

In jQuery, the most powerful character / symbol is the dollar sign. A $() function
normally returns a set of objects followed by a chain of operations. An example

$("div.test").add("p.quote").html

Think of it as a long sentence with punctuations. Indeed it is a chain of instructions to tell


the browser to do the following:

1. Get a div with class name is test;


2. Insert a paragraph with class name is quote;
3. Add a little text to the paragraph;
4. Operate on the DIV using a predefined method
called fadeout.

So there it is, the first two basics: $() and chainable.


jQuery Selectors

JQuery uses CSS selectors to single out one element or a group of elements, and
normally we use a combination of them to target specific elements. For example:

$(‘p.note’) returns all <p> elements whose class name is note;

$(‘p#note’) returns the <p> element whose id is note;

$(‘p’) returns all <p> elements

To select a child or children, we use the right angle bracket (>), as in $(‘p>a’)
(returns all of the hyper links within the <p> element);

To select element(s) with certain attributes, we use [], as in input[type=text]


(returns all text input element);

To select a container of some other elements, we use has keyword, for example: $
(‘p:has(a)’) (returns all <p> elements that contains an hyperlink);

jQuery also has a position-based selector for us to select elements by position, for
example $(‘p:first’)

Document.Ready()

The most commonly used command in jQuery is Document.Ready(). It makes sure


code is executed only when a page is fully loaded. We often place code blocks inside this
Document.Ready() event. For example:
$(document).ready(function(){
$("#buttonTest").click(function(
alert("I am ready!");
});
});

So far, we have brushed upon a bit of the core jQuery library. The true power of jQuery
lies in its speed and flexibility and extendibility, and the ever-growing however already
immense collection of jQuery plugins that deal with tasks big and small. As of today, by
the tally of jQuery.com, there are 1868 plug-ins, including 100 in AJAX, 123 in Animation
and effects, 66 in data, 321 in user interface. After all, JQuery is designed to be small
and nimble, providing only the core functionalities required in the most common
scenarios, and make others available only when needed and serve in the form of a plug-
in.

ASP .NET and JQuery

Long gone is the era when most computing was done on a desktop, when web pages
were more or less like virtual bulletin board. Now the impatient and internet-saturated
generation is insatiable with substance, dynamics and connectivity. They want rich
content, dazzling visual and instant feedback. More than ever, web development has
become a tight coordinated dance between server and client. The server does the heavy
lifting in the background, processes requests, churns up data and passes it back to the
requesting client; from which point the client computer takes over. Interactions now
taken place between web and user would be taken care by client side script, and web
server would only be involved when client initiates a new request for data operation. The
introduction and adoption of AJAX (the technique of performing asynchronous requests
through client scripts) is fueled by and fuels this trend.

While AJAX is now the unifying technique across browsers (IE or Firefox), platforms (PC
or MAC) and languages (C# or Java or PhP), it did not launch onto this popularity train
until just a few years ago, when Google showcased its power with an array of
applications. So with Google maps, Gmail, Google news, AJAX becomes the gold
messenger of server and client communication. As if overnight, more than 100 AJAX
libraries sprung up to simplify and smooth this process.

jQuery is one of the more effective and light-weighted ones. ASP .NET team has come up
with its own AJAX and JavaScript libraries in its unifying ambition to convert every
programmer (be it C# or VB or something else) into a Microsoft faithful. However, its
JavaScript library is considerably bulky, bandwidth-costly and poses a steep learning
curve.

On the other hand, ASP .NET has always been predominantly a server side technology,
web services and code behind page methods have always been the founding stones of
web applications. The development of ASP .NET AJAX helps developers to easily make
service calls from client side script.

Let’s take a look at how we can use jQuery to consume ASP .NET web services and page
methods.

Consuming ASP .NET web services using jQuery


From the conception to now, web services has gone a long way. Web services use XML as
the default data exchange format and SOAP as its protocol. However it has long been
dogged by complaints of complexity and lack of open standards. XML as its default
message format often feels cumbersome and bandwidth-heavy.

However, with AJAX, JSON overtook XML as a more efficient alternative. It retains all of
the advantages claimed by XML, such as being readable and writable for humans, and
easy to parse and generate. JSON, though completely language independent, borrows a
lot of conventions from languages such as C, C++, C#, Java, JavaScript, Perl, Python,
etc. This makes JSON an instant hit among programmers.

Tailored to accommodate this trend, data returned from ASP .NET web script services are
by default in JSON format.

JSON serialized web service

The following is a dummy ASP .NET web service. Please note that this service is adorned
with the ScriptService attribute that makes it available to JavaScript clients.

Listing 2: A Dummy web service


[WebService(Namespace = "htt
[WebServiceBinding(ConformsT
[System.Web.Script.Services.S
public class dummyWebservice
{

If we call the method sayHello and then use Firebug for Firefox to check the server
response, it would look like this:

A call (GET or POST) to ASP .NET JSON-serialized web services must meet two criteria:

• It must carry a HTTP Content-Type header with its


value set to application/json
• It must be called via the HTTP POST verb or else
the request would be rejected. To submit a GET request,
we just need to submit empty data string.

Consuming a web service using ASP .NET AJAX

It is easy to call web services with the native ASP .NET AJAX, which would automatically
take care all of the gritty details. It takes two steps:

First, add a ServiceReference to the ScriptManager control in the web form,


as such:
<asp:ScriptManager ID="_script
<Services>
<asp:ServiceReference Path
</Services>
</asp:ScriptManager>

Second, call any web methods defined in the web service by passing the necessary
parameters and a callback function. The callback will be invoked once the data is
returned from server. The following is a complete example of how we call a web service
using ASP .NET AJAX.

Listing 3: Calling a web service using ASP .NET AJAX


<%@ Page Language="C#" %>
<%@ Import Namespace="Syst
<!DOCTYPE html PUBLIC "-//W3C
"http://w w w .w 3.org/TR/xhtml1/
<html >

However as we have mentioned before, ASP .NET AJAX is rather heavy-handed and
carries hefty performance penalties. In comparison, jQuery is superior in its promise of
“less code do more”.

However how do call ASP .NET web services using jQuery?

Consuming a web service using jQuery

The answer: use the jQuery command ajax with the following syntax:

$.ajax (options)

It looks deceivingly simple. However, you can stuff a lot of specifics in this umbrella
parameter options, such as the required ones: url of the web service (url), request
content type (contentType), response data type (dataType), callback function for
success (success); and the optional ones: callback function in case of failure (error),
a timeout for the AJAX request in milliseconds (timeout), etc.

For example, we can call a specific web method in a web service as such.

Listing 4: JQuery .ajax command


$.ajax({
type: "POST",
contentType: "application/json;
url: "WebService.asmx/WebMe
data: "{}",
Two things are worth noting in the above JQuery AJAX call. First, we must specify the
contentType’s value as application/json; charset=utf-8, and the dataType
as json; second, to make a GET request, we leave the data value as empty.

So put it together, the following code demonstrates how we would use JQuery to call the
web service we created above.

Listing 5: Calling a web service using jQuery


<%@ Page Language="C#" %>
<%@ Import Namespace="Syst
<!DOCTYPE html PUBLIC "-//W3C
"http://w w w .w 3.org/TR/xhtml1/
<html >

Calling an ASP .NET page method

In terms of AJAX calls, a page method and a web service are almost interchangeable.
Page methods, as the name suggests, is page dependant. Rather than creating a stand-
alone web service, you can simple code a server-side method for data fetching and
processing and call it from your client-side script.

Here is how.

A dummy page method

The following is the code sample of a dummy page method that takes no parameters

Listing 6: A dummy hello world page method


[WebMethod()]
public static string sayHello()
{
return "hello ";
}

Please note that page methods must be declared as static, meaning a page method is
completely self-contained, and no page controls are accessible through the page method.
For example, if you have a textbox on the web form, there is no way the page method
can get or set its value. Consequently any changes with regards to the controls have no
affect on the page method. It is stateless and it does not carry any of the view-state data
typically carries around by an asp .NET page.

Calling a page method from jQuery

We use the same jQuery command $.ajax to call a page method, as shown in the
following example.
<script type="text/javascript">
$(document).ready(function
$.ajax({
type: "POST",
url: "pagemethod.aspx/

Client Templating

In ASP .NET, server side controls can be bound to a data source. Those controls are
essentially presentation templates. Many web applications have more or less abandoned
the server-centric programming model of ASP .NET. As a result, we have to retake up the
tasks of doing our own plumbing, of iterating through data and stuffing it in the right slot.

So for example, if we want to populate a table with data obtained from a web service,
without a proper template, we have manually iterate through records and weave all of
the data into a long string, peppered with events.

Let’s say we have a web service that returns a CD catalog, as such:

To display the data in a table, we might do the following

Listing 7: Data presentation without a template


function BuildTable(msg) {
var table = '<table><thead>
<tr><th>Art
<th>Comp
<th>Title<

How to use jTemplate

A much better alternative is that we use a template engine. jQuery has a few template
plugins, the most widely accepted is jTemplate. jTemplate is a JQuery template engine
that works with AJAX and JSON data. We can use Jtemplate in the following steps:

First, download the JQuery JavaScript file and reference it in your web page:
<scrip src="scripts/jQuery-jtemp

Second, define your template:

<script type="text/html" id="Tem


{#template MAIN}
<table cellpadding="10" cellspa
<tr>
<th>Artist</th>

Please note that we define the template in a script block, which can be accessed by its id;
also,“jTemplates uses python like syntax and the $T is a reference to the data item
passed to the template. Data can be passed in as an object and you can reference the
object’s properties off this $T data item.” (Rick Strahl)

Third, call your web service in your script, designate the template and instantiate it with
data.

$(document).ready(function() {
$.ajax({
type: "POST",
url: "CDCatalog.asmx/G
data: "{}",

Figure 4: Using jTemplate to display a CD catalog

ASP .NET client templating engine

In July 2008, the ASP .NET team also announced its own client template engine, as
blogged by Bertrand Le Roy. It uses {{expression}} as place holder for data, it
works with JavaScript and AJAX. The ASP .NET client template engine also allows live
bindings (dynamic data refreshing and updates). For more information, please read Using
client templates, part 2: Live Bindings.

The following is how we can populate an ASP .NET client template engine with the data
we get from the above CD catalog web service.

Listing 8: ASP .NET AJAX client templating engine


<!DOCTYPE html PUBLIC "-//W3C
<html xmlns="http://w w w .w 3.o
<head>
<link href="template.css" rel=
</head>

As we can see, the ASP .NET client template engine is very simple and elegant. However,
it is still at its early stage. The template is still lacking in flexibility and it still waits to be
widely tested and accepted by the developers community.

Summary

With the marching forward of AJAX to the forefront of building rich interactive web sites,
jQuery as the lightweight yet powerful JavaScript library also gains ever more
prominence. In late 2008, Microsoft ASP .NET officially partners with jQuery to develop
better and more efficient approaches to speed and smooth the communication between
servers and client. Reflecting on the trend of harnessing the best of the web, this article
paints in broad strokes some of the characteristics of jQuery and how we can integrate
jQuery into ASP .NET.

ASP.NET State Management Overview

A new instance of the Web page class is created each time the page is posted to the
server. In traditional Web

programming, this would typically mean that all information associated with the page and
the controls on the

page would be lost with each round trip. For example, if a user enters information into a
text box, that

information would be lost in the round trip from the browser or client device to the
server.

To overcome this inherent limitation of traditional Web programming, ASP.NET


includes several options that help

you preserve data on both a per-page basis and an application-wide basis. These features
are as follows:

View state
Control state

Hidden fields

Cookies

Query strings

Application state

Session state

Profile Properties

View state, control state, hidden fields, cookies, and query strings all involve storing data
on the client in

various ways. However, application state, session state, and profile properties all store
data in memory on the

server. Each option has distinct advantages and disadvantages, depending on the scenario.

Client-Based State Management Options


--------------------------------------------------------------------------------

The following sections describe options for state management that involve storing
information either in the page

or on the client computer. For these options, no information is maintained on the server
between round trips.

View State
The ViewState property provides a dictionary object for retaining values between
multiple requests for the same

page. This is the default method that the page uses to preserve page and control property
values between round

trips.

When the page is processed, the current state of the page and controls is hashed into a
string and saved in the

page as a hidden field, or multiple hidden fields if the amount of data stored in the
ViewState property exceeds
the specified value in the MaxPageStateFieldLength property. When the page is posted
back to the server, the

page parses the view-state string at page initialization and restores property information
in the page.

You can store values in view state as well. For more information on using View State, see
ASP.NET View State

Overview. For recommendations about when you should use view state, see ASP.NET
State Management

Recommendations.

Control State
Sometimes you need to store control-state data in order for a control to work properly.
For example, if you have

written a custom control that has different tabs that show different information, in order
for that control to

work as expected, the control needs to know which tab is selected between round trips.
The ViewState property

can be used for this purpose, but view state can be turned off at a page level by
developers, effectively

breaking your control. To solve this, the ASP.NET page framework exposes a feature in
ASP.NET called control

state.

The ControlState property allows you to persist property information that is specific to a
control and cannot be

turned off like the ViewState property.

Hidden Fields
ASP.NET allows you to store information in a HiddenField control, which renders as a
standard HTML hidden field.

A hidden field does not render visibly in the browser, but you can set its properties just as
you can with a

standard control. When a page is submitted to the server, the content of a hidden field is
sent in the HTTP form
collection along with the values of other controls. A hidden field acts as a repository for
any page-specific

information that you want to store directly in the page.

Security Note
It is easy for a malicious user to see and modify the contents of a hidden field. Do not
store any information

in a hidden field that is sensitive or that your application relies on to work properly. For
more information,

see ASP.NET State Management Recommendations.

A HiddenField control stores a single variable in its Value property and must be
explicitly added to the page.

For more information, see HiddenField Web Server Control Overview.

In order for hidden-field values to be available during page processing, you must submit
the page using an HTTP

POST command. If you use hidden fields and a page is processed in response to a link or
an HTTP GET command, the

hidden fields will not be available. For usage recommendations, see ASP.NET State
Management Recommendations.

Cookies
A cookie is a small amount of data that is stored either in a text file on the client file
system or in-memory

in the client browser session. It contains site-specific information that the server sends to
the client along

with page output. Cookies can be temporary (with specific expiration times and dates) or
persistent.

You can use cookies to store information about a particular client, session, or application.
The cookies are

saved on the client device, and when the browser requests a page, the client sends the
information in the cookie
along with the request information. The server can read the cookie and extract its value.
A typical use is to

store a token (perhaps encrypted) indicating that the user has already been authenticated
in your application.

Security Note
The browser can only send the data back to the server that originally created the cookie.
However, malicious

users have ways to access cookies and read their contents. It is recommended that you do
not store sensitive

information, such as a user name or password, in a cookie. Instead, store a token in the
cookie that identifies

the user, and then use the token to look up the sensitive information on the server.

For more information about using cookies, see Cookies and ASP.NET State Management
Recommendations.

Query Strings
A query string is information that is appended to the end of a page URL. A typical query
string might look like

the following example:

Copyhttp://www.contoso.com/listwidgets.aspx?category=basic&price=100

In the URL path above, the query string starts with a question mark (?) and includes two
attribute/value pairs,

one called "category" and the other called "price."

Query strings provide a simple but limited way to maintain state information. For
example, they are an easy way

to pass information from one page to another, such as passing a product number from one
page to another page

where it will be processed. However, some browsers and client devices impose a 2083-
character limit on the

length of the URL.


Security Note
Information that is passed in a query string can be tampered with by a malicious user. Do
not rely on query

strings to convey important or sensitive data. Additionally, a user can bookmark the URL
or send the URL to

other users, thereby passing that information along with it. For more information, see
ASP.NET State Management

Recommendations and How to: Protect Against Script Exploits in a Web Application by
Applying HTML Encoding to

Strings.

In order for query string values to be available during page processing, you must submit
the page using an HTTP

GET command. That is, you cannot take advantage of a query string if a page is
processed in response to an HTTP

POST command. For usage recommendations, see ASP.NET State Management


Recommendations.

Server-Based State Management Options


--------------------------------------------------------------------------------

ASP.NET offers you a variety of ways to maintain state information on the server, rather
than persisting

information on the client. With server-based state management, you can decrease the
amount of information sent

to the client in order to preserve state, however it can use costly resources on the server.
The following

sections describe three server-based state management features: application state, session
state, and profile

properties.

Application State
ASP.NET allows you to save values using application state — which is an instance of the
HttpApplicationState
class — for each active Web application. Application state is a global storage mechanism
that is accessible from

all pages in the Web application. Thus, application state is useful for storing information
that needs to be

maintained between server round trips and between requests for pages. For more
information, see ASP.NET

Application State Overview.

Application state is stored in a key/value dictionary that is created during each request to
a specific URL. You

can add your application-specific information to this structure to store it between page
requests.

Once you add your application-specific information to application state, the server
manages it. For usage

recommendations, see ASP.NET State Management Recommendations.

Session State
ASP.NET allows you to save values by using session state — which is an instance of the
HttpSessionState class —

for each active Web-application session. For an overview, see ASP.NET Session State
Overview.

Session state is similar to application state, except that it is scoped to the current browser
session. If

different users are using your application, each user session will have a different session
state. In addition,

if a user leaves your application and then returns later, the second user session will have a
different session

state from the first.

Session state is structured as a key/value dictionary for storing session-specific


information that needs to be

maintained between server round trips and between requests for pages. For more
information, see ASP.NET Session
State Overview.

You can use session state to accomplish the following tasks:

Uniquely identify browser or client-device requests and map them to an individual


session instance on the

server.

Store session-specific data on the server for use across multiple browser or client-device
requests within the

same session.

Raise appropriate session management events. In addition, you can write application code
leveraging these

events.

Once you add your application-specific information to session state, the server manages
this object. Depending

on which options you specify, session information can be stored in cookies, on an out-of-
process server, or on a

computer running Microsoft SQL Server. For usage recommendations, see ASP.NET
State Management Recommendations.

Profile Properties
ASP.NET provides a feature called profile properties, which allows you to store user-
specific data. This feature

is similar to session state, except that the profile data is not lost when a user's session
expires. The

profile-properties feature uses an ASP.NET profile, which is stored in a persistent format


and associated with

an individual user. The ASP.NET profile allows you to easily manage user information
without requiring you to

create and maintain your own database. In addition, the profile makes the user
information available using a

strongly typed API that you can access from anywhere in your application. You can store
objects of any type in
the profile. The ASP.NET profile feature provides a generic storage system that allows
you to define and

maintain almost any kind of data while still making the data available in a type-safe
manner.

To use profile properties, you must configure a profile provider. ASP.NET includes a
SqlProfileProvider class

that allows you to store profile data in a SQL database, but you can also create your own
profile provider class

that stores profile data in a custom format and to a custom storage mechanism such as an
XML file, or even to a

web service.

Because data that is placed in profile properties is not stored in application memory, it is
preserved through

Internet Information Services (IIS) restarts and worker-process restarts without losing
data. Additionally,

profile properties can be persisted across multiple processes such as in a Web farm or a
Web garden. For more

information, see ASP.NET Profile Properties Overview.

Partial Classes in ASP.NET


Partial class is a new functionality that is included in Visual Studio .Net 2005 and is
supported in ASP.Net 2.0. This new functionality helps you to split a single class into
multiple partial classes. These partial classes can be in different individual files.

In the earlier versions of Visual Studio .Net 2005, while you create an ASP.Net
application, you might have seen that a single class has to be in a single file. You will
be beginning a class and ending that class in the same file. It was not possible to
split a single class across multiple files. This new feature, partial class, allows you to
allot different developers to develop the code for different functionalities that are
available in a single class. These functionalities can be developed in partial classes
and then compiled to form the required assembly.

In the previous versions of the Visual Studio .Net IDE, when you create a new
ASP.Net webform, the name of the web form is used as a class in the code-behind
file. Apart from that, you would have seen lots of code generated by Visual Studio
.Net itself. In the latest version of the Visual Studio .Net IDE, the codes that are
generated by Visual Studio .Net are in a separate file as a partial class. Hence a user
who creates a new webform would see a partial class for that page, when the user
uses the code-behind file. This way the code that is seen in the code-behind file is
minimal for a particular webform.

The compilers for VB.Net or C# look for the partial classes and integrate them while
compiling, to form the intermediate language. This intermediate language is the
same when compared to the intermediate language that is generated, if all the
partial classes are combined to form a single class in a single file. There is no
modification done in the CLR for the implementation of partial classes.

Let us look at a sample code for the implementation of the partial classes. The code
would have an interface which is implemented across different classes. When
compiled, the compiler would integrate all the partial classes and see whether all the
methods of the interface have been implemented. If it is not, then the compiler will
throw an error. If all the interfaces are implemented then it will compile to form the
intermediate language. The code given below gives the implementation of the partial
classes.

'-----File_1.vb
Imports System
Interface IPartialClass
Sub PrintEmployeeName(ByVal sName As String)
Sub PrintEmployeeName()
End Interface

Partial Class MyPartialClass


Private sName As String = "sName Variable - John Peter - From Partial Class."
End Class

'-----File_2.vb
Imports System
Partial Public Class MyPartialClass
Implements IPartialClass

Public Sub PrintEmployeeName(string str)


Response.Write(str)
End Sub
End Class

'-----File_3.vb
Imports System
Partial Public Class MyPartialClass
Public Sub PrintEmployeeName()
Response.Write(sName)
End Sub
End Class

'-----Write the following code in the click event of a button control '-----in the .aspx
page
Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim PClass as New MyPartialClass()
PClass.PrintEmployeeName("String from a Partial Class.")
PClass.PrintEmployeeName()
End Sub

There are three class files namely, File_1.vb, File_2.vb, and File_3.vb. The first file
has the interface IPartialClass declared and a partial class MyPartialClass which
declares a string variable. The second file has the same partial class which
implements the interface IPartialClass. This interface has two methods to be
implemented. The first method is implemented in the second file and the second
method is implemented in the third file. Altogether, all the methods are implemented
in some partial class. It is not necessary for the class in the first file File_1.vb to
have the Partial keyword. But if you are writing your code for partial classes in C#, it
is necessary for all the classes to have the ‘partial’ keyword. This is a significant
difference between VB.Net and C# in using partial classes. Note that the method
PrintEmployeeName() is implemented in the third file File_3.vb and the method
PrintEmployeeName(string str) is implemented in the second file File_2.vb. The
string variable sName that is used in the third file is declared in the first file
File_1.vb.

Create a new webform in your project and add a button control. In the click event of
the button control, write the code which calls both the methods of the interface as
given in the above code listing. Upon compilation, the .aspx page will execute
properly displaying the appropriate strings. This proves that although the classes are
split in different files, the usage of the Partial keyword helps in binding all the partial
classes together during compilation and produces a single intermediate language file.
The CLR finds no difference in the intermediate language, even if the IL is produced
by having a single class in a single class file, where all the methods of the interface
are implemented in a single class in a single class file. Since we are dealing with
different files for a single class, even if you missed out implementing one method of
an interface, the intellisense of Visual Studio .Net 2005 will point it out to you, thus
enabling you to implement the missed out method of the interface. This is one
among the advantage of using a Visual Studio .Net 2005 IDE for ASP.Net 2.0
applications.

This type of splitting the class file is particularly useful if a single class runs to
thousands of lines of code with different functionalities across different methods.
Productivity of the project team is increased since a single class file is split across the
team members and implemented as partial classes.

You might also like