ajax in asp.net mvc ajax, partial page rendering, jquery ajax, mvc ajax helpers softuni team...

Click here to load reader

Post on 18-Jan-2016

233 views

Category:

Documents

2 download

Embed Size (px)

TRANSCRIPT

ASP.NET Identity System

AJAX in ASP.NET MVCAJAX, Partial Page Rendering, jQuery AJAX, MVC AJAX HelpersSoftUni TeamTechnical TrainersSoftware Universityhttp://softuni.bg

ASP.NET MVC Software University Foundation http://softuni.orgThis work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.12What is AJAX?Raw AJAX vs. AJAX using a JS LibraryPartial Page Rendering vs. JSON ServiceAJAX with Unobtrusive JavaScriptAJAX MVC HelpersActionLink and BeginFormPartial Views and AJAXJSON, AJAX and ASP.NET MVCTable of Contents

What is AJAX?Asynchronous JavaScript and XML

4AJAX is acronym of Asynchronous JavaScript and XMLAJAX == technique for asynchronously loading (in the background) of dynamic Web content and data from the Web server into a HTML pageAllows dynamically changing the DOM (client-side) in Web applicationsTwo styles of AJAXPartial page rendering Load an HTML fragment and display it in a JSON service with client-side renderingLoading a JSON object and render it at the client-side with JS / jQueryAJAX

5AJAX advantagesAsynchronous calls data is loaded after the page is shownMinimal data transfer less traffic, fast updateResponsiveness better user experienceAJAX disadvantagesRequires more development effortsThe browser [Back] and [Refresh] buttons don't workMight cause SEO problems: search engine bots may skip the AJAXAJAX: Pros and Cons

6Browsers support XMLHttpRequest objectExposes a JavaScript API to send raw AJAX requestsSendHTTP/HTTPSrequests directly to theWeb serverGET / POST / PUT / DELETE / otherAJAX response might be JSON, XML, HTML, asplain text, etc.Same-origin policyhttps://en.wikipedia.org/wiki/Same-origin_policyAJAX requests can only access the same server that served the original Web page executing the AJAX call

The XMLHttpRequest Object7function updateServerTimeAjax() { var xhr = new XMLHttpRequest(); xhr.open("GET", "/Home/ServerTime", true); xhr.onreadystatechange = function() { var timeDiv = document.getElementById("timeDisplay"); timeDiv.innerHTML = ''; if (xhr.readyState == 4 && xhr.status == 200) { timeDiv.innerHTML = xhr.responseText; } } xhr.send();}Raw AJAX ExampleThe request is finished and the response is readyHTTP status code is "200 OK"8AJAX with jQuery ExamplejQuery dramatically simplifies working with AJAX:

Get Server Time

function updateServerTimeAjax () { $("#timeDisplay").load("/Home/ServerTime"); }

AJAX with Unobtrusive JavaScript

Unobtrusive JavaScript == no script is injected into page Only data-attributes to configure the AJAX call settingsRequires Microsoft.jQuery.Unobtrusive.Ajax NuGet packagejquery.unobtrusive-ajax.js (AJAX helpers)AJAX with Unobtrusive JavaScript & jQuery

Load Server Time

10 Software University Foundation http://softuni.orgThis work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.10AJAX Helpers in ASP.NET [email protected] and @Ajax.BeginForm

12AJAX helpers add AJAX functionality to ASP.NET MVCTwo core features of AJAX helpers:Invoke an action method asynchronously using AJAXUse the Ajax.ActionLink() helperSubmit an entire form using AJAXUse the Ajax.BeginForm() helperAJAX helpers use AjaxOptions object with configurationsAJAX Helpers in ASP.NET MVC1213Url URL to send request HttpMethod request method (GET / POST / PUT / DELETE / )InsertionMode how to handle the received dataInsertAfter, InsertBefore or ReplaceUpdateTargetId HTML element to be changedLoadingElementId show / hide "Loading" when loadingEvents (JavaScript functions)OnSuccess, OnFailure, OnBegin, OnCompleteAjaxOptions Object14Defines an action link () for loading data with AJAXAjax.ActionLink Helper [email protected]("Load Server Time", "ServerTime", null, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "timeDisplay", LoadingElementId = "timeDisplayLoading", InsertionMode = InsertionMode.Replace, OnBegin = "OnAjaxRequestBegin", OnFailure = "OnAjaxRequestFailure", OnSuccess = "OnAjaxRequestSuccess", OnComplete = "OnAjaxRequestComplete",}, new { @class = "btn btn-primary" })actioncontroller15A form that submits AJAX request and renders a partial viewAjax.BeginForm Helper [email protected] (Ajax.BeginForm("Search", new AjaxOptions { UpdateTargetId = "results", InsertionMode = InsertionMode.Replace })){ }

@Html.Partial("_BookResult", Model)16Return a PartialView to the helpers (view without the layout)

Ajax.BeginForm Helper Example (2)public ActionResult Search(string query){ var result = BooksData .GetAll() .AsQueryable() .Where(book => book.Title.Contains(query)) .Select(BookViewModel.FromBook) .ToList();

return this.PartialView("_BookResult", result);}JSON Services in ASP.NET MVC

18MVC Ajax Helpers cover simple AJAX scenariosReplacing HTML content Partial page rendering Other scenarios require some JavaScriptAuto-complete textboxesClient-side validationInvoking JSON services and render content at the client-sideAnimationsJSON Services in ASP.NET MVC19Return JsonResult in the action

Use jQuery.getJSON()MVC, JSON Results and JavaScript Renderingpublic JsonResult AllBooks(){ var books = BooksData.GetAll(); return this.Json(books, JsonRequestBehavior.AllowGet);}jQuery.getJSON("AllBooks", null, function(data) { jQuery(data).each(function (index, element) { var newBookElement = $("+element.Title+""); $("#books").append(newBookElement); });});20AJAX is powerful technique in Web developmentLoad data asynchronouslyWithout refreshing the entire Web pageAJAX Helpers in ASP.NET MVC simplify AJAX callsControllers return partial views, displayed on the Web pageUse ActionLink and BeginForm for simple AJAX callsStill we can implement JSON service with client-side renderingTypically use jQuery AJAX functionalitySummary

AJAX in ASP.NET MVC

https://softuni.bg/trainings/1230/asp-net-mvc-october-2015

Questions??????????SoftUni Diamond Partners

LicenseThis course (slides, examples, demos, videos, homework, etc.)is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license23

Attribution: this work may contain portions from"ASP.NET MVC" course by Telerik Academy under CC-BY-NC-SA license Software University Foundation http://softuni.orgThis work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.23Free Trainings @ Software UniversitySoftware University Foundation softuni.orgSoftware University High-Quality Education, Profession and Job for Software Developerssoftuni.bg Software University @ Facebookfacebook.com/SoftwareUniversitySoftware University @ YouTubeyoutube.com/SoftwareUniversitySoftware University Forums forum.softuni.bg

Software University Foundation http://softuni.orgThis work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.24