62
Создание ASP.NET приложений при помощи AJAX, JQuery и Visual Studio 2010 Денис Резник Digital Cloud Technologies

MS Swit 2010

  • Upload
    -

  • View
    1.050

  • Download
    0

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: MS Swit 2010

Создание ASP.NET приложений при помощи AJAX, JQuery и Visual Studio 2010

Денис РезникDigital Cloud Technologies

Page 2: MS Swit 2010

Модель работы Запрос-Ответ

Page 3: MS Swit 2010

Работа без перезагрузки страницы

Page 4: MS Swit 2010

Как это работаетCLIENT

SERVER

TRANSPORT

HTTP

XML HTTP Request Object

DOM, JavaScript, CSS, XML, JSON, etc.

C#, VB.NET, ASPX, XML, SQL, etc.

Web Service

Business Logic Application Data

Business Logic Application Data

Page 5: MS Swit 2010

AJAXfunction createRequestObject(){    if (window.XMLHttpRequest) {     try {    return new XMLHttpRequest();    } catch (e){}    } else if (window.ActiveXObject) {    try {    return new ActiveXObject('Msxml2.XMLHTTP');    } catch (e){    try {    return new

ActiveXObject('Microsoft.XMLHTTP');    } catch (e){}    }    }

    return null;}

Page 7: MS Swit 2010

ASP.NET AJAX

Page 8: MS Swit 2010

Составные части ASP.NET AJAX

Page 9: MS Swit 2010

Update Panel

• Самая популярная штука• Частичный рендеринг страницы

– Автоматическое преобразование постбеков в асинхронные колбеки

– Автоматическое обновление контента при помощи результатов колбека

– Не нужно никаких знаний JavaScript или XmlHttpRequest

• Высокоуровневая надстройка над XmlHttpRequest– Преимущества: Крайне просто в

использовании– Недостатки: Менее эффективено чем

класический AJAX

Page 10: MS Swit 2010

Update Panel

Browser Web Server

Browser submits HTTPrequest to server

1

Server responds with content;browser renders that content

2

Browser submits async XML-HTTP request to server; UIremains responsive; pagedoesn't flash

3

XML-HTTP request completes;JavaScript refreshes portion ofpage affected by response

4

Page 11: MS Swit 2010

AJAX Toolkit

• Самый популярный проект на CodePlex

> 25 000 скачиваний каждую неделю

• Легко интегрируется в Visual Studio 2010

• Идеально подходит для Web Forms проектов

Page 12: MS Swit 2010

AJAX и SEO

Page 13: MS Swit 2010

AJAX и SEO

• AJAX – плохо для SEO• Поисковые роботы любят чистый HTML• Убедитесь, что у вас есть URL для каждой

"страницы", которую вы хотите показать роботам и желаете, чтобы она была проиндексирована

• Загрузите часть контента с ключевыми словами не динамически

• Разделы меню, ссылки и другие важные структурные аспекты сайта должны работать без AJAX и/или JavaScript

Page 14: MS Swit 2010

Индексация AJAX контента

Page 15: MS Swit 2010

AJAX CDN

• CDN (Content Delivery Network) — географически распределённая сетевая инфраструктура, позволяющая оптимизировать доставку контента конечным пользователям

Page 16: MS Swit 2010

AJAX CDN

Page 17: MS Swit 2010
Page 18: MS Swit 2010

Использование AJAX CDNПодгрузка скриптов c CDN

Page 19: MS Swit 2010

AJAX Library Client Side is dead. Почему?

Потому что jQuery

Page 20: MS Swit 2010

jQuery

Page 21: MS Swit 2010

Почему jQuery это круто?

• Легковесный и быстрый фреймворк

• Огромное комьюнити (в которое входит и Майкрософт)

• Скрывает от разработчиков множество низкоуровневых вещей

• Множество плагинов• Интуитивно понятный синтаксис

$('#something').hide().css('background', 'red').fadeIn();

Page 22: MS Swit 2010

Кто использует jQuery?

http://jquery.com/

Page 23: MS Swit 2010

Статистика использования

Page 24: MS Swit 2010

jQuery Mobile

http://jquerymobile.com/

Page 25: MS Swit 2010

Microsoft & jQuery

1997: Classic ASP 1, 2, 32002: ASP.NET 1.0 and WebForms

Ajax Control Toolkit2003 to 2007: ASP.NET 1.1, 2, 3, 3.52008: Visual Studio 2008 - including jQuery2008: Official Support for jQuery 2009: ASP.NET MVC – including jQuery2009: ASP.NET Ajax Library2009: jQuery on the Microsoft CDN2010: ASP.NET 4 – including jQuery

Page 26: MS Swit 2010

ДемоВключение Intellisence для jQuery в Visual Studio 2010

Page 27: MS Swit 2010

jQuery(Selectors)

Page 28: MS Swit 2010

Selectors

//Selects all the anchor tags in the DOM$('a')

//Selects all the anchor tags inside of div elements in the DOM$('div a')

//Selects all the elements with a class of 'odd'$('.odd')

//Selects all the tr elements with a class of 'odd'$('tr.odd')

Page 29: MS Swit 2010

Selectors

// Selects all links that ends with mp3 in the href$("a[href$='mp3']")

// Selects all links that are set to open a new window$("a[target='_blank']")

// Selects all links that have a class that begins with "custom"$("a[class^='custom']")

Page 30: MS Swit 2010

Selectors

// Selects all the input elements$(':input')

// Selects all the disabled input elements$(':disabled')

// Selects the 4rd (0 based) list item$('li:eq(3)')

// Selects links to pdf that are children of a list item$('li > a[href$=pdf]')

// Selects list items that have links inside of them$('li:has(a)')

Page 31: MS Swit 2010

Selector Context

// use "span a" selector to find the link$('span a.myClass').addClass('highlight');

// Start at #myDiv context & use "span a" selector to find the link$('span a.myClass', '#myDiv').addClass('highlight');

Page 32: MS Swit 2010

Caching Selectors

// Uncached code$('#myButton').click(function() {

$('#alertMessage').hide();$('#alertMessage').html('<b>Really Bad Error

</b>');$('#alertMessage').fadeIn('slow');

});

// Cached code$('#myButton').click(function() {

var $alertMessage = $('#alertMessage');$alertMessage.hide();$alertMessage.html('<b>Really Bad Error</b>');$alertMessage.fadeIn('slow');

});

Page 33: MS Swit 2010

Caching Selectors

// Chaining$('#myButton').click(function() {

$('#alertMessage').hide().html('<b>Really Bad Error</b>').fadeIn('slow');

});

Page 34: MS Swit 2010

ДемоSelectorGadget

http://www.selectorgadget.com/

Page 35: MS Swit 2010

jQuery(Storing Data)

Page 36: MS Swit 2010

Storing Data (Bad Practice)

//Storing special information about the anchor in the alt attribute$('a').attr('alt', 'Special info about this HTML tag');

//Getting the special information from the anchor's alt attribute$('a').attr('alt')

Page 37: MS Swit 2010

Storing Data (Best Practice)

// Storing a complex data structure under the specialInfo key$('a').data('specialInfo', {

firstName: 'Denis',lastName: 'Reznik'});

//Getting the complex data structure specialInfo & accessing the firstName property$('a').data('specialInfo').firstName;

Page 38: MS Swit 2010

Storing Data (Best Practice)

$("li.demo").data({firstName: “Denis", lastName: “Reznik“

});

console.dir($("li.demo").data());

$("li.demo").data("someKey",{ firstName: “John", lastName: “Smith“

});

console.dir($("li.demo").data());console.log($("li.demo").data().someKey.firstName);

Page 39: MS Swit 2010

jQuery(Events)

Page 40: MS Swit 2010

Event Bubbling<ul id="sites">

<li><a id="microsoft"

href="http://www.microsoft.com"> microsoft</a>

</li> <li>

<a id="jquery" href="http://www.jquery.com"> jquery</a>

</li> <li>

<a id="google" href="http://www.google.com"> google</a>

</li> <li>

<a id="facebook" href="http://www.facebook.com"> facebook</a>

</li></ul>

Page 41: MS Swit 2010

Event binding

// bind couple of eventsvar clickMe = function() {

console.log('Hello World!');};

$("p.clickMe").click(clickMe).dblclick(clickMe);

// Another variant of binding$("p.clickMe").bind("click dblclick", clickMe);

Page 42: MS Swit 2010

Event unbinding

//really dangerous$("p.clickMe").unbind();

//moderately dangerous$("p.clickMe").unbind("click dblclick");

//safe$("p.clickMe").unbind("click dblclick", clickMe);

Page 43: MS Swit 2010

Live and Die

// Dynamic Hello will not have click handler$("p.sayHello").bind('click', function() {

console.log('Hello World!');});$('body').append("<p class='sayHello'>Dynamic Hello</p>");

// Dynamic Hello will have click handler$("p.sayHello").live('click', function() {

console.log('Hello World!');});/* die() || die("click") || die("click", clickMe) */$('body').append("<p class='sayHello'>Dynamic Hello</p>");

Page 44: MS Swit 2010

Preventing default behavior

// Preventing event bubbling$('a').click(function () {

return false;});

return false = e.preventDefault() + e.stopPropagation

// Doesn't prevent event bubbling$('a').click(function (e) {

e.preventDefault();});

Page 45: MS Swit 2010

Delegate and Undelegate

// Event will not bubble upvar clickMe = function() {

var element = $(this);element.text(element.text() + ' :)');

};

$("ul.demo").delegate("li", "click", clickMe);/* undelegate(), undelegate("li", "click"),undelegate("li", "click", clickMe) */$("ul.demo").append("<li>Dynamic Item</li>");

Page 46: MS Swit 2010

jQuery(AJAX)

Page 47: MS Swit 2010

Использование AJAX в jQuery

• Базовый метод для подгрузки контента с сервера:– load()

• url• parameters: данные которые будут передаваться

(string, object...). Если указаны, идёт POST, если нет - GET

• callback (optional)

• Наряду с load() можно использовать $.get()/$.getJson() or $.post()

$('#someDiv').load('test.html',function () { ('Load was performed.'); });

Page 48: MS Swit 2010

Использование AJAX в jQuery

• Если необходим больший контроль над AJAX запросом, используем:– $.ajax()

• options: определяет объект, содержащий все параметры для запроса

• Когда параметров много, используем– $.ajaxSetup

• options: определяет объект, содержащий все параметры для запроса, который становится дефолтным для всех Ajax запросов

Page 49: MS Swit 2010

Использование AJAX в jQuery

$.ajax({url: 'document.xml',type: 'GET',

dataType: 'xml',timeout: 1000,error: function () {

alert('Error loading XML document');},success: function (xml) {

// do something with xml}

});$('#stats').load('stats.html');

Page 50: MS Swit 2010

Использование AJAX в jQuery

$.ajaxSetup ({ cache: false

});

$.ajaxSetup({type: 'POST',timeout: 5000,dataType: 'html'

});

Page 51: MS Swit 2010

ДемоИспользование AJAX в jQuery

Page 52: MS Swit 2010

Свежие новости!

• 3 новых плагина от Microsoft– jQuery Templates– jQuery Data Link– jQuery Globalization

• Теперь это официальные плагины• Будут частью jQuery (в версии 1.5)

Page 53: MS Swit 2010

jQuery Templates

• Шаблоны это разметка HTML (содержащая символы подстановки)

• 3 метода:– .tmpl(): рендерит шаблон– .tmplItem(): находит шаблонный

элемент– .template(): компилирует шаблон

<script id="movieTemplate" type="text/x-jquery-tmpl"><li><b>${Name}</b> (${ReleaseYear})</li>

</script>

Page 54: MS Swit 2010

.tmpl()

• Берёт шаблон и рендерит его контент, используя определённый набор данных

• .tmpl( [ data ], [ options ] )– Data: Данные для рендеринга. Может быть

любого типа, включая Array и Object– Options: дополнительный набор пар ключ-

значение, определяемых пользователем

• Может использоваться в связке с локальными данными, и удалёнными данными (ajax)

$("#myTemplate").tmpl(myData)

Page 55: MS Swit 2010

ДемоИспользование jQuery Templates

Page 56: MS Swit 2010

jQuery Data Link

• Data linking – механизм привязки данных в jQuery– Позволяет связывать поле объекта с

полем другого объекта– Связвание происходит через

функцию .link()

– Когда значение поля меняется, свойство связанного объекта также меняется

• По-умолчаниию связывание двустороннее

var person = {};$("form").link(person);

Page 57: MS Swit 2010

ДемоjQuery Data Link

Page 58: MS Swit 2010

jQuery Globalization

• Содержит в себе информацию о более чем 350 (!) культурах– Валюта– Формат даты (вкючая названия

месяцев)– Числовые форматы

• Использование стандартизированных идентификаторов культуры (uk-ua, и т.д.)

Page 59: MS Swit 2010

ДемоjQuery Globalization

Page 60: MS Swit 2010

Summary

• Легковесный и легкий в использовании JavaScript фреймворк

• Кросс-браузерность, сокрытие низкоуровневых деталей

• Понятная модель событий• Может работать с MVC и WebForms• Легко расширяем

Page 61: MS Swit 2010

Welcome to the Party!!!

Page 62: MS Swit 2010

Денис РезникРуководитель департамента разработки, DCTTrainer, Microsoft Innovation CenterMicrosoft MVP (SQL Server)Microsoft Certified [email protected]://reznik.uneta.com.ua/http://twitter.com/DenisReznikMCPD - Web Developer 4MCITP – Database Developer 2008MCTS - .NET Framework 4, Web ApplicationsMCTS - SQL Server 2008, Database DevelopmentMCTS - .NET Framework 4, Data Access with ADO.NETMCTS - SQL Server 2008, Implementation and MaintenanceMCITP - SQL Server 2008, Implementation and Maintenance