SlideShare a Scribd company logo
ASP.NET MVCÖNSEL AKIN
Controllers & Actions
ControllersResponsible for controlling the flow of applicationExposes public methods as actionsEach action returns different results typesInherits from System.Web.Mvc.Controller
Returning Action ResultsViewResult			View()PartialViewResult		PartialView()RedirectResult			Redirect()ContentResult			Content()JsonResult			Json()FileResult			File()EmptyResult			HttpUnauthorizedResultJavaScriptResult		JavaScript()RedirectToRouteResult	RedirectToRoute()
Returning View ResultsReturns HTML to the browserImplicit vs Explicit view namingreturn View();return View(‘’ViewName’’)Specifying pathsreturn View(‘’SubFolder/ViewName’’)return View(‘’~/View.aspx’’)
Returning Redirect ResultsSame controllerreturn RedirectToAction(‘’Index’’);Different controllerreturn RedirectToAction(‘’Product’’, ‘’List’’);Providing route valuesreturn RedirectToAction(‘’Product’’, ‘’Details’, new { id = 20 });
Returning Content Resultsreturn Content(‘’Hello’’);Returning .Net typespublic string HelloAction() {return ‘’Hello’’;}ToString() and wrapping with ContentResult
Returning Json ResultsReturns result in JavaScript Object Notation (JSON) formatUses JavaScriptSerializer{ id: 10, name: ‘SharePoint 2010’, authors: [{ ‘onsela’, ‘mehmeta’ }]}var books = new List<Book>();return Json(books);
Returning JavaScriptpublic ActionResult ShowMessage() {return JavaScript(‘’alert(‘Message!’);’’);}// View.aspx<%: Ajax.ActionLink(‘’Show message’’, ‘’ShowMessage’’, null) %>
Accessing Request Information
Action Method Parameters – 1public ActionResult ShowInfo(string city) {	// Equivalent tovar tempCity = Request.Form[‘’city’’];}Optional ParametersNullable typesDefaultValueAttributeOptional Parameters with C# 4.0Complex Parameterspublic ActionResult Update(Product p) { .... }
Action Method Parameters – 2Invoking model binding manuallypublic ActionResult Update(int productID) {var product = repository.Get(productID);UpdateModel(product);repository.Update(product);return View(product);}
Passing Data to Views – 1Controllers and views are totally independentControllers suply data to viewsNo way to access controllers from viewsSupplying data from a controllerViewData[‘’product’’] = productObject;Accessing data from the view<%: ((Product)ViewData[‘’product’’]).Name %>
Passing Data to Views – 2Sending strongly typed objects to viewspublic ActionResult ProductInfo(int id) {var product = repository.Get(id);return View(product);}// View.aspxProduct Name: <%: Model.Name %>
Passing Data to Views – 3Passing dynamic objects to viewspublic 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 TempDataSimilar usage with ViewDataPreserves data across redirectionspublic 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 FiltersInjects extra behaviors to controller and actionsDerive from FilterAttribute classBasic types of filters
Applying Filters[Authorize(Roles=‘’Administrator’’)]public class ProductController : Controller {	[OutputCache(Duration=30)]public ActionResult Save(Product p) {}}
How Filters are Executedtry{Run each IAuthorizationFilter'sOnAuthorization() methodif(none of the IAuthorizationFilters cancelled execution)	{Run each IActionFilter'sOnActionExecuting() method		Run the action methodRun each IActionFilter'sOnActionExecuted() method (in reverse order)Run each IResultFilter'sOnResultExecuting() method		Run the action resultRun 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() methodRun any action result set by the exception filters}
IActionFilter, IResultFilter Methods
Authorize FilterRun early in the requestUsers propertyRoles propertyOrder property[Authorize(Roles=‘’SalesRep’’, Users=‘’onsela’’)]public ActionResult ProductList() {	return View();}
HandleError FilterDetects exceptionsRenders a specific viewReturns HTTP status code 500 to clients[HandleError(View=‘’ErrorPage’’, 	ExceptionType=typeof(SqlException)]public ActionResult ProductList() {	return View();}
OutputCache Filter
Handling Unknown Actionspublic class HomeController : Controller{	protected override void HandleUnknownAction(string 		actionName)	{		.....	}}

More Related Content

What's hot (20)

PPT
Sessi
Asif Atick
 
PPTX
Part 26 login type2 using binding source count
Girija Muscut
 
PPTX
React outbox
Angela Lehru
 
PDF
Unidirectional Data Flow in Swift
Jason Larsen
 
PPTX
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
PDF
React & Redux
Federico Bond
 
PDF
Dmytro Zaitsev Viper: make your mvp cleaner
Аліна Шепшелей
 
PDF
Aspnet Life Cycles Events
LiquidHub
 
PPTX
Introduction to react and redux
Cuong Ho
 
PPTX
Redux training
dasersoft
 
PPTX
Web technology javascript
Uma mohan
 
PDF
React state managmenet with Redux
Vedran Blaženka
 
PDF
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
Inhacking
 
PPTX
React / Redux Architectures
Vinícius Ribeiro
 
PPTX
SUGCon 2014 Sitecore MVC
mikeedwards83
 
PPTX
Lesson 05 Data Binding in WPF
Quang Nguyễn Bá
 
PDF
React JS and Redux
Glib Kechyn
 
PPTX
Lesson 06 Styles and Templates in WPF
Quang Nguyễn Bá
 
PPT
Intention Oriented Model Interaction
Yasir Karam
 
PPT
10 01 containersbindings
tflung
 
Sessi
Asif Atick
 
Part 26 login type2 using binding source count
Girija Muscut
 
React outbox
Angela Lehru
 
Unidirectional Data Flow in Swift
Jason Larsen
 
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
React & Redux
Federico Bond
 
Dmytro Zaitsev Viper: make your mvp cleaner
Аліна Шепшелей
 
Aspnet Life Cycles Events
LiquidHub
 
Introduction to react and redux
Cuong Ho
 
Redux training
dasersoft
 
Web technology javascript
Uma mohan
 
React state managmenet with Redux
Vedran Blaženka
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
Inhacking
 
React / Redux Architectures
Vinícius Ribeiro
 
SUGCon 2014 Sitecore MVC
mikeedwards83
 
Lesson 05 Data Binding in WPF
Quang Nguyễn Bá
 
React JS and Redux
Glib Kechyn
 
Lesson 06 Styles and Templates in WPF
Quang Nguyễn Bá
 
Intention Oriented Model Interaction
Yasir Karam
 
10 01 containersbindings
tflung
 

Similar to ASP.NET MVC Controllers & Actions (20)

PPT
ASP .net MVC
Divya Sharma
 
PPTX
Asp.Net Mvc
micham
 
PPTX
Developing ASP.NET Applications Using the Model View Controller Pattern
goodfriday
 
PPTX
Asp.net mvc
erdemergin
 
PPT
ASP.NET MVC introduction
Tomi Juhola
 
PPT
ASP.net MVC CodeCamp Presentation
buildmaster
 
PDF
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
PPS
Introduction To Mvc
Volkan Uzun
 
PPTX
ASP.NET MVC controllers
Mahmoud Tolba
 
PPT
Introduction to ASP.NET MVC
Maarten Balliauw
 
PDF
Mvc3 crash
Melick Baranasooriya
 
PDF
Asp.Net MVC Framework Design Pattern
maddinapudi
 
PPT
CTTDNUG ASP.NET MVC
Barry Gervin
 
PPTX
MVC Training Part 1
Lee Englestone
 
PPTX
Build your web app with asp.net mvc 2 from scratch
Chalermpon Areepong
 
PPTX
MVC & SQL_In_1_Hour
Dilip Patel
 
PPTX
ASP.MVC Training
Mahesh Sikakolli
 
PPTX
Chapter4.pptx
narendrakumar406336
 
PPT
Inside asp.net mvc framework
Ciklum Ukraine
 
PPT
Inside ASP.NET MVC framework
Ciklum Ukraine
 
ASP .net MVC
Divya Sharma
 
Asp.Net Mvc
micham
 
Developing ASP.NET Applications Using the Model View Controller Pattern
goodfriday
 
Asp.net mvc
erdemergin
 
ASP.NET MVC introduction
Tomi Juhola
 
ASP.net MVC CodeCamp Presentation
buildmaster
 
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Introduction To Mvc
Volkan Uzun
 
ASP.NET MVC controllers
Mahmoud Tolba
 
Introduction to ASP.NET MVC
Maarten Balliauw
 
Asp.Net MVC Framework Design Pattern
maddinapudi
 
CTTDNUG ASP.NET MVC
Barry Gervin
 
MVC Training Part 1
Lee Englestone
 
Build your web app with asp.net mvc 2 from scratch
Chalermpon Areepong
 
MVC & SQL_In_1_Hour
Dilip Patel
 
ASP.MVC Training
Mahesh Sikakolli
 
Chapter4.pptx
narendrakumar406336
 
Inside asp.net mvc framework
Ciklum Ukraine
 
Inside ASP.NET MVC framework
Ciklum Ukraine
 
Ad

ASP.NET MVC Controllers & Actions

  • 3. ControllersResponsible for controlling the flow of applicationExposes public methods as actionsEach action returns different results typesInherits from System.Web.Mvc.Controller
  • 5. Returning View ResultsReturns HTML to the browserImplicit vs Explicit view namingreturn View();return View(‘’ViewName’’)Specifying pathsreturn View(‘’SubFolder/ViewName’’)return View(‘’~/View.aspx’’)
  • 6. Returning Redirect ResultsSame controllerreturn RedirectToAction(‘’Index’’);Different controllerreturn RedirectToAction(‘’Product’’, ‘’List’’);Providing route valuesreturn RedirectToAction(‘’Product’’, ‘’Details’, new { id = 20 });
  • 7. Returning Content Resultsreturn Content(‘’Hello’’);Returning .Net typespublic string HelloAction() {return ‘’Hello’’;}ToString() and wrapping with ContentResult
  • 8. Returning Json ResultsReturns result in JavaScript Object Notation (JSON) formatUses JavaScriptSerializer{ id: 10, name: ‘SharePoint 2010’, authors: [{ ‘onsela’, ‘mehmeta’ }]}var books = new List<Book>();return Json(books);
  • 9. Returning JavaScriptpublic ActionResult ShowMessage() {return JavaScript(‘’alert(‘Message!’);’’);}// View.aspx<%: Ajax.ActionLink(‘’Show message’’, ‘’ShowMessage’’, null) %>
  • 11. Action Method Parameters – 1public ActionResult ShowInfo(string city) { // Equivalent tovar tempCity = Request.Form[‘’city’’];}Optional ParametersNullable typesDefaultValueAttributeOptional Parameters with C# 4.0Complex Parameterspublic ActionResult Update(Product p) { .... }
  • 12. Action Method Parameters – 2Invoking model binding manuallypublic ActionResult Update(int productID) {var product = repository.Get(productID);UpdateModel(product);repository.Update(product);return View(product);}
  • 13. Passing Data to Views – 1Controllers and views are totally independentControllers suply data to viewsNo way to access controllers from viewsSupplying data from a controllerViewData[‘’product’’] = productObject;Accessing data from the view<%: ((Product)ViewData[‘’product’’]).Name %>
  • 14. Passing Data to Views – 2Sending strongly typed objects to viewspublic ActionResult ProductInfo(int id) {var product = repository.Get(id);return View(product);}// View.aspxProduct Name: <%: Model.Name %>
  • 15. Passing Data to Views – 3Passing dynamic objects to viewspublic 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 TempDataSimilar usage with ViewDataPreserves data across redirectionspublic 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 FiltersInjects extra behaviors to controller and actionsDerive from FilterAttribute classBasic 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 Executedtry{Run each IAuthorizationFilter'sOnAuthorization() methodif(none of the IAuthorizationFilters cancelled execution) {Run each IActionFilter'sOnActionExecuting() method Run the action methodRun each IActionFilter'sOnActionExecuted() method (in reverse order)Run each IResultFilter'sOnResultExecuting() method Run the action resultRun 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() methodRun any action result set by the exception filters}
  • 21. Authorize FilterRun early in the requestUsers propertyRoles propertyOrder property[Authorize(Roles=‘’SalesRep’’, Users=‘’onsela’’)]public ActionResult ProductList() { return View();}
  • 22. HandleError FilterDetects exceptionsRenders a specific viewReturns HTTP status code 500 to clients[HandleError(View=‘’ErrorPage’’, ExceptionType=typeof(SqlException)]public ActionResult ProductList() { return View();}
  • 24. Handling Unknown Actionspublic class HomeController : Controller{ protected override void HandleUnknownAction(string actionName) { ..... }}