SlideShare une entreprise Scribd logo
1  sur  24
ASP.NET MVC ÖNSEL AKIN
Controllers & Actions
Controllers Responsible for controlling the flow of application Exposes public methods as actions Each action returns different results types Inherits from System.Web.Mvc.Controller
Returning Action Results ViewResult			View() PartialViewResult		PartialView() RedirectResult			Redirect() ContentResult			Content() JsonResult			Json() FileResult			File() EmptyResult			 HttpUnauthorizedResult JavaScriptResult		JavaScript() RedirectToRouteResult	RedirectToRoute()
Returning View Results Returns HTML to the browser Implicit vs Explicit view naming return View(); return View(‘’ViewName’’) Specifying paths return View(‘’SubFolder/ViewName’’) return View(‘’~/View.aspx’’)
Returning Redirect Results Same controller return RedirectToAction(‘’Index’’); Different controller return RedirectToAction(‘’Product’’, ‘’List’’); Providing route values return RedirectToAction(‘’Product’’, ‘’Details’, new { id = 20 });
Returning Content Results return Content(‘’Hello’’); Returning .Net types public string HelloAction() { return ‘’Hello’’; } ToString() and wrapping with ContentResult
Returning Json Results Returns result in JavaScript Object Notation (JSON) format Uses JavaScriptSerializer {  id: 10, name: ‘SharePoint 2010’,  authors: [{ ‘onsela’, ‘mehmeta’ }] } var books = new List<Book>(); return Json(books);
Returning JavaScript public ActionResult ShowMessage() { return JavaScript(‘’alert(‘Message!’);’’); } // View.aspx <%: Ajax.ActionLink(‘’Show message’’, ‘’ShowMessage’’, null) %>
Accessing Request Information
Action Method Parameters – 1 public ActionResult ShowInfo(string city) { 	// Equivalent to var tempCity = Request.Form[‘’city’’]; } Optional Parameters Nullable types DefaultValueAttribute Optional Parameters with C# 4.0 Complex Parameters public ActionResult Update(Product p) { .... }
Action Method Parameters – 2 Invoking model binding manually public ActionResult Update(int productID) { var product = repository.Get(productID); UpdateModel(product); repository.Update(product); return View(product); }
Passing Data to Views – 1 Controllers and views are totally independent Controllers suply data to views No way to access controllers from views Supplying data from a controller ViewData[‘’product’’] = productObject; Accessing data from the view <%: ((Product)ViewData[‘’product’’]).Name %>
Passing Data to Views – 2 Sending strongly typed objects to views public ActionResult ProductInfo(int id) { var product = repository.Get(id); return View(product); } // View.aspx Product Name: <%: Model.Name %>
Passing Data to Views – 3 Passing dynamic objects to views public ActionResult ProductDetails(int id) { dynamic model = new ExpandoObject(); model.Product = repository.Get(id); model.Message = ‘’Out of Stock’; return View(model); } // View.aspx <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> Product: <%: Model.Product.Name %> Message: <%: Model.Message %>
Using TempData Similar usage with ViewData Preserves data across redirections public ActionResult Update(Product product) { repository.Update(product); TempData[‘’message’’] = ‘’Product ‘’ + product.Name + ‘’ updated.’’; return RedirectToAction(‘’Success’’); } // Success action view.aspx <% if (TempData[‘’message’’] != null) %> <p><%: TempData[‘’message’’] %></p> <% } %>
Using Filters Injects extra behaviors to controller and actions Derive from FilterAttribute class Basic types of filters
Applying Filters [Authorize(Roles=‘’Administrator’’)] public class ProductController : Controller { 	[OutputCache(Duration=30)] public ActionResult Save(Product p) { } }
How Filters are Executed try { Run each IAuthorizationFilter'sOnAuthorization() method if(none of the IAuthorizationFilters cancelled execution) 	{ Run each IActionFilter'sOnActionExecuting() method 		Run the action method Run each IActionFilter'sOnActionExecuted() method (in reverse order) Run each IResultFilter'sOnResultExecuting() method 		Run the action result Run each IResultFilter'sOnResultExecuted() method (in reverse order) 	} 	else 	{ Run any action result set by the authorization filters 	} } catch(exception not handled by any action or result filter) { Run each IExceptionFilter'sOnException() method Run any action result set by the exception filters }
IActionFilter, IResultFilter Methods
Authorize Filter Run early in the request Users property Roles property Order property [Authorize(Roles=‘’SalesRep’’, Users=‘’onsela’’)] public ActionResult ProductList() { 	return View(); }
HandleError Filter Detects exceptions Renders a specific view Returns HTTP status code 500 to clients [HandleError(View=‘’ErrorPage’’, 	ExceptionType=typeof(SqlException)] public ActionResult ProductList() { 	return View(); }
OutputCache Filter
Handling Unknown Actions public class HomeController : Controller { 	protected override void HandleUnknownAction(string 		actionName) 	{ 		..... 	} }

Contenu connexe

Tendances

Part 26 login type2 using binding source count
Part 26 login type2 using binding source countPart 26 login type2 using binding source count
Part 26 login type2 using binding source countGirija Muscut
 
Unidirectional Data Flow in Swift
Unidirectional Data Flow in SwiftUnidirectional Data Flow in Swift
Unidirectional Data Flow in SwiftJason Larsen
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular ComponentsSquash Apps Pvt Ltd
 
Aspnet Life Cycles Events
Aspnet Life Cycles EventsAspnet Life Cycles Events
Aspnet Life Cycles EventsLiquidHub
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and reduxCuong Ho
 
Redux training
Redux trainingRedux training
Redux trainingdasersoft
 
Web technology javascript
Web technology   javascriptWeb technology   javascript
Web technology javascriptUma mohan
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with ReduxVedran Blaženka
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...Inhacking
 
SUGCon 2014 Sitecore MVC
SUGCon 2014 Sitecore MVCSUGCon 2014 Sitecore MVC
SUGCon 2014 Sitecore MVCmikeedwards83
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and ReduxGlib Kechyn
 
Lesson 06 Styles and Templates in WPF
Lesson 06 Styles and Templates in WPFLesson 06 Styles and Templates in WPF
Lesson 06 Styles and Templates in WPFQuang Nguyễn Bá
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model InteractionYasir Karam
 
10 01 containersbindings
10 01 containersbindings10 01 containersbindings
10 01 containersbindingstflung
 

Tendances (20)

Sessi
SessiSessi
Sessi
 
Part 26 login type2 using binding source count
Part 26 login type2 using binding source countPart 26 login type2 using binding source count
Part 26 login type2 using binding source count
 
React outbox
React outboxReact outbox
React outbox
 
Unidirectional Data Flow in Swift
Unidirectional Data Flow in SwiftUnidirectional Data Flow in Swift
Unidirectional Data Flow in Swift
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Dmytro Zaitsev Viper: make your mvp cleaner
Dmytro Zaitsev Viper: make your mvp cleanerDmytro Zaitsev Viper: make your mvp cleaner
Dmytro Zaitsev Viper: make your mvp cleaner
 
Aspnet Life Cycles Events
Aspnet Life Cycles EventsAspnet Life Cycles Events
Aspnet Life Cycles Events
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and redux
 
Redux training
Redux trainingRedux training
Redux training
 
Web technology javascript
Web technology   javascriptWeb technology   javascript
Web technology javascript
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
 
SUGCon 2014 Sitecore MVC
SUGCon 2014 Sitecore MVCSUGCon 2014 Sitecore MVC
SUGCon 2014 Sitecore MVC
 
Lesson 05 Data Binding in WPF
Lesson 05 Data Binding in WPFLesson 05 Data Binding in WPF
Lesson 05 Data Binding in WPF
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and Redux
 
Lesson 06 Styles and Templates in WPF
Lesson 06 Styles and Templates in WPFLesson 06 Styles and Templates in WPF
Lesson 06 Styles and Templates in WPF
 
Intention Oriented Model Interaction
Intention Oriented Model InteractionIntention Oriented Model Interaction
Intention Oriented Model Interaction
 
10 01 containersbindings
10 01 containersbindings10 01 containersbindings
10 01 containersbindings
 

Similaire à ASP.NET MVC Essentials

Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvcmicham
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllersMahmoudOHassouna
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanGigin Krishnan
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Ruud van Falier
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsallanh0526
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXIMC Institute
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introductionTomi Juhola
 

Similaire à ASP.NET MVC Essentials (20)

ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllers
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 

ASP.NET MVC Essentials

  • 3. Controllers Responsible for controlling the flow of application Exposes public methods as actions Each action returns different results types Inherits from System.Web.Mvc.Controller
  • 4. Returning Action Results ViewResult View() PartialViewResult PartialView() RedirectResult Redirect() ContentResult Content() JsonResult Json() FileResult File() EmptyResult HttpUnauthorizedResult JavaScriptResult JavaScript() RedirectToRouteResult RedirectToRoute()
  • 5. Returning View Results Returns HTML to the browser Implicit vs Explicit view naming return View(); return View(‘’ViewName’’) Specifying paths return View(‘’SubFolder/ViewName’’) return View(‘’~/View.aspx’’)
  • 6. Returning Redirect Results Same controller return RedirectToAction(‘’Index’’); Different controller return RedirectToAction(‘’Product’’, ‘’List’’); Providing route values return RedirectToAction(‘’Product’’, ‘’Details’, new { id = 20 });
  • 7. Returning Content Results return Content(‘’Hello’’); Returning .Net types public string HelloAction() { return ‘’Hello’’; } ToString() and wrapping with ContentResult
  • 8. Returning Json Results Returns result in JavaScript Object Notation (JSON) format Uses JavaScriptSerializer { id: 10, name: ‘SharePoint 2010’, authors: [{ ‘onsela’, ‘mehmeta’ }] } var books = new List<Book>(); return Json(books);
  • 9. Returning JavaScript public ActionResult ShowMessage() { return JavaScript(‘’alert(‘Message!’);’’); } // View.aspx <%: Ajax.ActionLink(‘’Show message’’, ‘’ShowMessage’’, null) %>
  • 11. Action Method Parameters – 1 public ActionResult ShowInfo(string city) { // Equivalent to var tempCity = Request.Form[‘’city’’]; } Optional Parameters Nullable types DefaultValueAttribute Optional Parameters with C# 4.0 Complex Parameters public ActionResult Update(Product p) { .... }
  • 12. Action Method Parameters – 2 Invoking model binding manually public ActionResult Update(int productID) { var product = repository.Get(productID); UpdateModel(product); repository.Update(product); return View(product); }
  • 13. Passing Data to Views – 1 Controllers and views are totally independent Controllers suply data to views No way to access controllers from views Supplying data from a controller ViewData[‘’product’’] = productObject; Accessing data from the view <%: ((Product)ViewData[‘’product’’]).Name %>
  • 14. Passing Data to Views – 2 Sending strongly typed objects to views public ActionResult ProductInfo(int id) { var product = repository.Get(id); return View(product); } // View.aspx Product Name: <%: Model.Name %>
  • 15. Passing Data to Views – 3 Passing dynamic objects to views public ActionResult ProductDetails(int id) { dynamic model = new ExpandoObject(); model.Product = repository.Get(id); model.Message = ‘’Out of Stock’; return View(model); } // View.aspx <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> Product: <%: Model.Product.Name %> Message: <%: Model.Message %>
  • 16. Using TempData Similar usage with ViewData Preserves data across redirections public ActionResult Update(Product product) { repository.Update(product); TempData[‘’message’’] = ‘’Product ‘’ + product.Name + ‘’ updated.’’; return RedirectToAction(‘’Success’’); } // Success action view.aspx <% if (TempData[‘’message’’] != null) %> <p><%: TempData[‘’message’’] %></p> <% } %>
  • 17. Using Filters Injects extra behaviors to controller and actions Derive from FilterAttribute class Basic types of filters
  • 18. Applying Filters [Authorize(Roles=‘’Administrator’’)] public class ProductController : Controller { [OutputCache(Duration=30)] public ActionResult Save(Product p) { } }
  • 19. How Filters are Executed try { Run each IAuthorizationFilter'sOnAuthorization() method if(none of the IAuthorizationFilters cancelled execution) { Run each IActionFilter'sOnActionExecuting() method Run the action method Run each IActionFilter'sOnActionExecuted() method (in reverse order) Run each IResultFilter'sOnResultExecuting() method Run the action result Run each IResultFilter'sOnResultExecuted() method (in reverse order) } else { Run any action result set by the authorization filters } } catch(exception not handled by any action or result filter) { Run each IExceptionFilter'sOnException() method Run any action result set by the exception filters }
  • 21. Authorize Filter Run early in the request Users property Roles property Order property [Authorize(Roles=‘’SalesRep’’, Users=‘’onsela’’)] public ActionResult ProductList() { return View(); }
  • 22. HandleError Filter Detects exceptions Renders a specific view Returns HTTP status code 500 to clients [HandleError(View=‘’ErrorPage’’, ExceptionType=typeof(SqlException)] public ActionResult ProductList() { return View(); }
  • 24. Handling Unknown Actions public class HomeController : Controller { protected override void HandleUnknownAction(string actionName) { ..... } }