Вы находитесь на странице: 1из 12

Aplicando jQuery en ASP.

NET
jQuery es un framework que facilita el uso de Javascript en las
aplicaciones Web.
Existen diferentes frameworks en Internet, algunos de ellos de pago,
pero jQuery es uno de los ms extendidos y usados en aplicaciones
Web en general.
Microsoft entabl una comunicacin directa con los desarrolladores de
jQuery, y ahora est integrado en el entorno rpido de desarrollo.
El objetivo de jQuery o de un framework de JavaScript es el de
simplificar la interactuacin de JavaScript con los documentos o
pginas HTML, pudiendo acceder al rbol DOM de forma directa y
sencilla, tarea que sin este tipo de frameworks se hace muy
engorrosa.
Otra de las funcionalidades de jQuery es la posibilidad de crear
efectos mucho ms vistosos para nuestras aplicaciones Web, lo cual
representa una interactuacin del usuario mucho ms rica que las
aplicaciones Web tradicionales.
A continuacin, veremos como utilizar de manera sencilla jQuery en
Visual Studio, como medida introductoria.

Usando jQuery en ASP.NET
Antes de mostrar como empezar a usar jQuery en ASP.NET, vamos a
escribir una aplicacin Web que tenga el siguiente cdigo HTML:
<span style="background-color:#C0C0C0; font-size: 22pt;"
onclick="alert(!aludos""#$%&lsa'e(<)span#
Este cdigo, nos mostrar en pantalla una caja de mensaje con el
texto Saludos.
Ahora bien, lo que hemos hecho es usar JavaScript puro y duro, sin
embargo, tambin podemos hacer esto mismo pero con jQuery,
separando el cdigo del control, a una parte de la pgina Web donde
podamos localizar y cambiar rpidamente su cdigo sin apenas
esfuerzo, y de una forma ms natural.
Antes de continuar, vamos a indicar un par de comentarios respecto a
jQuery.
Sin nimo de introducirnos en un tutoial de jQuery, debo mencionar
que jQuery tiene un ncleo que corresponde con el carcter $.
A travs del ncleo, seremos capaces de acceder a cualquier conjunto
de elementos del DOM. De esta manera, $(document) indicar la
parte principal de la pgina o documento Web.
De la misma manera, si queremos detectar el momento en el que se
completa la carga de una pgina Web, deberemos usar el
mtodo ready.
Evidentemente, si queremos utilizar todo el conjunto, es decir, detectar
cuando se ha cargado el documento, la combinacin es natural:$
(document).ready.
Todo esto, comentado de forma resumida como es obvio.
El caso es que la carga de un documento Web se produce en el
evento window.onload, pero tambin podemos utilizar a jQuery como
hemos comentado anteriormente con ready.
Cabe destacar que primero se lanza la carga de document, y luego el
evento onload de la pgina.
Esto se ve muy bien en el siguiente ejemplo:
<*t'l +'lns="*ttp:)),,,-,.-org)/000)+*t'l"#
<*ead runat="ser1er"#
<title#<)title#
<script src="!cripts)23uery-/-.-2-2s"
type="te+t)2a1ascript"#<)script#
<script type="te+t)2a1ascript"#
4(docu'ent"-ready(function (" 5
alert(6esde 4(docu'ent"-ready";
7";
function 'i8uncion("
5
alert(6esde onload";
7
<)script#
<)*ead#
<body onload="'i8uncion(";"#
<for' id="for'/" runat="ser1er"#
<)for'#
<)body#
<)*t'l#
En este ejemplo, se lanza primero como hemos mencionado el
mensaje preparado en jQuery, y posteriormente el evento onload de la
pgina HTML.
Ahora bien, si nos fijamos en el cdigo del ejemplo, observaremos que
para usar jQuery hemos hecho referencia al framework de jQuery que
reside en nuestro caso en el directorio Scripts.
Sin embargo, vamos a hacer otro ejemplo que muestre como
interactuar con los elementos HTML o controles de una pgina Web y
jQuery.
<*t'l +'lns="*ttp:)),,,-,.-org)/000)+*t'l"#
<*ead runat="ser1er"#
<title#<)title#
<script src="!cripts)23uery-/-.-2-2s"
type="te+t)2a1ascript"#<)script#
<script type="te+t)2a1ascript"#
4(docu'ent"-ready(function (" 5
4(#click9pcion"-click(function (" 5
alert($!aludos desde 2:uery(";
7";
7";
<)script#
<)*ead#
<body#
<for' id="for'/" runat="ser1er"#
<span style="background-color:#C0C0C0; font-size: 22pt;"
id="click9pcion"#$%&lsa'e(<)span#
<)for'#
<)body#
<)*t'l#
En este ejemplo, podemos observar que en la etiqueta span hemos
indicado un identificador clickOpction, y que dentro del cdigo jQuery
hemos hecho referencia a esa etiqueta mediante el uso de $
('#clickOpcion'), lo cual nos permite actuar con respecto al evento o
accin realizada sobre esa etiqueta span.
Como podemos ver, el uso de jQuery es muy sencillo en ASP.NET.
Aqu no vamos a tocar ningn curso de jQuery, para eso estn
los tutoriales de jQuery.
Sirva este captulo como captulo introductorio de como empezar a
abordar un ejemplo de jQuery en ASP.NET.
Tenga en cuenta adems, que jQuery puede ser utilizado en
combinacin con los controles Ajax de ASP.NET, o bien, se pueden
usar las libreras Ajax propias de jQuery. Como puede apreciar, jQuery
nos ofrece muchas combinaciones posibles para crear nuestras
aplicaciones Web.
A continuacin, veremos como llevar a cabo otro ejemplo de jQuery,
similar al anterior pero tratando de cambiar un texto de la pgina Web.
Dentro de nuestra pgina Web, escribiremos el siguienet cdigo:
<*t'l +'lns="*ttp:)),,,-,.-org)/000)+*t'l"#
<*ead runat="ser1er"#
<title#<)title#
<script src="!cripts)23uery-/-.-2-2s"
type="te+t)2a1ascript"#<)script#
<script type="te+t)2a1ascript"#
4(docu'ent"-ready(function (" 5
4(#click9pcion"-click(function (" 5
ca'biar;e+to("$!aludos desde 2:uery("";
7";
7";
function ca'biar;e+to('essage" 5
1ar di1/ = docu'ent-get<le'ent=y>d("di1/"";
di1/-inner?;@A = 'essage;
7
<)script#
<)*ead#
<body#
<for' id="for'/" runat="ser1er"#
<span style="background-color:#C0C0C0; font-size: 22pt;"
id="click9pcion"#$%&lsa'e(<)span#
<br )#
<di1 id="di1/"#<)di1#
<)for'#
<)body#
<)*t'l#
Al hacer clic sobre el contenido de la etiqueta span, se lanza el evento
de carga del formulario y con l, se llama a la
funcin cambiarTexto que a su vez, busca la etiqueta div1.
Esta bsqueda se lleva a cabo a travs de otra funcin de
nombra getElementById que permite localizar el control, para actuar
sobre l de forma directa.
En este caso, para cambiar el texto de la etiqueta referenciada.
Como podemos apreciar, estos ejemplos se lanzan en el lado cliente,
sin necesidad de recargar la pgina, lo cual permite grandes
posibilidades en nuestras aplicaciones Web.
Quizs ya supiera usar JavaScript y piense que esto ya era posible
hacerlo antes, y es as, pero lo ventajoso de jQuery es adems de los
efectos y funcionalidades, la posibilidad de actuar sobre el DOM de
forma mucho ms directa y efectiva, simplificando mucho las tareas
que antes costaba varias lneas de cdigo ms, dejando incluso el
cdigo mucho ms claro.
1.About jQuery
1.1. How jQuery Works
jQuery: The Basics
This is a basic tutorial, designed to help you get started using jQuery. If you don't
have a test page setup yet, start by creating the following HTML page:
1
2
3
4
5
6
7
8
9
10
11
12
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>

)) Bour code goes *ere-

</script>
</body>
</html>
13
14
15
16
The src attribute in the <script> element must point to a copy of jQuery.
Download a copy of jQuery from the Downloading jQuery page and store
the jquery.js file in the same directory as your HTML file.
linkLaunching Code on Document eady
To ensure that their code runs after the browser finishes loading the document,
many JavaScript programmers wrap their code in an oload function:
1
2
3
4
5
!ido!.oload = function"# $

alert" "!elcome" #%

&
Unfortunately, the code doesn't run until all images are finished downloading,
including banner ads. To run code as soon as the document is ready to be
manipulated, jQuery has a statement known as the ready event:
1
2
3
4
5
'" documet #.ready"function"# $

)) Bour code *ere-

&#%
For example, inside the ready event, you can add a click handler to the link:
1
'" documet #.ready"function"# $

'" "a" #.clic("function" e)et # $
2
3
4
5
6
7
8
9

alert" "*ha(s for )isiti+," #%

&#%

&#%
Save your HTML file and reload the test page in your browser. Clicking the link
should now first display an alert pop-up, then continue with the default behavior of
navigating to http://jquery.com.
For clic( and most other events, you can prevent the default behavior by
calling e)et.pre)etDefault"# in the event handler:
1
2
3
4
5
6
7
8
9
10
11
'" documet #.ready"function"# $

'" "a" #.clic("function" e)et # $

alert" "-s you ca see. the li( o lo+er too( you to jquery.com" #%

e)et.pre)etDefault"#%

&#%

&#%
linkCom!lete "#am!le
The following example illustrates the click handling code discussed above,
embedded directly in the HTML <body>. Note that in practice, it is usually better to
place your code in a separate JS file and load it on the page with
a <script> element's srcattribute.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>

'" documet #.ready"function"# $
'" "a" #.clic("function" e)et # $
alert" "*he li( !ill o lo+er ta(e you to jquery.com" #%
e)et.pre)etDefault"#%
&#%
&#%

</script>
</body>
</html>
link$dding and emo%ing an HT&L Class
Important: You must place the remaining jQuery examples inside the ready event
so that your code executes when the document is ready to be worked on.
Another common task is adding or removing a class.
First, add some style information into the <head> of the document, like this:
1
2
3
4
5
<style>
a.test $
fot-!ei+ht: bold%
&
</style>
Next, add the .addClass() call to the script:
1
'" "a" #.add/lass" "test" #%
All <a> elements are now bold.
To remove an existing class, use .removeClass():
1
'" "a" #.remo)e/lass" "test" #%
link'!ecial "((ects
jQuery also provides some handy effects to help you make your web sites stand
out. For example, if you create a click handler of:
1
2
3
4
5
6
'" "a" #.clic("function" e)et # $

e)et.pre)etDefault"#%

'" this #.hide" "slo!" #%

&#%
7
Then the link slowly disappears when clicked.
linkCallbacks and Functions
Unlike many other programming languages, JavaScript enables you to freely pass
functions around to be executed at a later time. A callback is a function that is
passed as an argument to another function and is executed after its parent function
has completed. Callbacks are special because they patiently wait to execute until
their parent finishes. Meanwhile, the browser can be executing other functions or
doing all sorts of other work.
To use callbacks, it is important to know how to pass them into their parent
function.
linkCall)ack without $rguments
If a callback has no arguments, you can pass it in like this:
1
'.+et" "myhtmlpa+e.html". my/all0ac( #%
When $.get() finishes getting the page myhtmlpa+e.html, it executes
the my/all0ac("# function.
Note: The second parameter here is simply the function name (but not as a
string, and without parentheses).
linkCall)ack with $rguments
Executing callbacks with arguments can be tricky.
linkWrong
This code example will not work:
1
'.+et" "myhtmlpa+e.html". my/all0ac(" param1. param2 # #%
The reason this fails is that the code executes my/all0ac(" param1.
param2 # immediately and then passes my/all0ac("#'sreturn value as the second
parameter to '.+et"#. We actually want to pass the function my/all0ac("#,
not my/all0ac(" param1. param2 #'s return value (which might or might not be a
function). So, how to pass in my/all0ac("# and include its arguments?
linkRight
To defer executing my/all0ac("# with its parameters, you can use an anonymous
function as a wrapper. Note the use of fuctio"# $. The anonymous function
does exactly one thing: calls my/all0ac("#, with the values of param1 and param2.
1
2
3
4
5
'.+et" "myhtmlpa+e.html". function"# $

my/all0ac(" param1. param2 #%

&#%
When '.+et"# finishes getting the page myhtmlpa+e.html, it executes the
anonymous function, which executes my/all0ac(" param1. param2 #.

Вам также может понравиться