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

PPTX
Controllers & actions
PPTX
Detail view in distributed technologies
PDF
Data Binding and Data Grid View Classes
PPTX
User controls
PPTX
Data Binding - Android by Harin Trivedi
PPT
Dev308
PPTX
Grid Vew Control VB
Controllers & actions
Detail view in distributed technologies
Data Binding and Data Grid View Classes
User controls
Data Binding - Android by Harin Trivedi
Dev308
Grid Vew Control VB

What's hot (20)

PPT
Sessi
PPTX
Part 26 login type2 using binding source count
PPTX
React outbox
PDF
Unidirectional Data Flow in Swift
PPTX
Sharing Data Between Angular Components
PDF
React & Redux
PDF
Dmytro Zaitsev Viper: make your mvp cleaner
PDF
Aspnet Life Cycles Events
PPTX
Introduction to react and redux
PPTX
Redux training
PPTX
Web technology javascript
PDF
React state managmenet with Redux
PDF
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
PPTX
React / Redux Architectures
PPTX
SUGCon 2014 Sitecore MVC
PPTX
Lesson 05 Data Binding in WPF
PDF
React JS and Redux
PPTX
Lesson 06 Styles and Templates in WPF
PPT
Intention Oriented Model Interaction
PPT
10 01 containersbindings
Sessi
Part 26 login type2 using binding source count
React outbox
Unidirectional Data Flow in Swift
Sharing Data Between Angular Components
React & Redux
Dmytro Zaitsev Viper: make your mvp cleaner
Aspnet Life Cycles Events
Introduction to react and redux
Redux training
Web technology javascript
React state managmenet with Redux
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
React / Redux Architectures
SUGCon 2014 Sitecore MVC
Lesson 05 Data Binding in WPF
React JS and Redux
Lesson 06 Styles and Templates in WPF
Intention Oriented Model Interaction
10 01 containersbindings
Ad

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

PPT
ASP .net MVC
PPTX
Asp.Net Mvc
PPTX
Developing ASP.NET Applications Using the Model View Controller Pattern
PPTX
Asp.net mvc
PPT
ASP.NET MVC introduction
PPT
ASP.net MVC CodeCamp Presentation
PDF
Mvc interview questions – deep dive jinal desai
PPS
Introduction To Mvc
PPTX
ASP.NET MVC controllers
PPT
Introduction to ASP.NET MVC
PDF
PDF
Asp.Net MVC Framework Design Pattern
PPT
CTTDNUG ASP.NET MVC
PPTX
MVC Training Part 1
PPTX
Build your web app with asp.net mvc 2 from scratch
PPTX
MVC & SQL_In_1_Hour
PPTX
ASP.MVC Training
PPTX
Chapter4.pptx
PPT
Inside asp.net mvc framework
PPT
Inside ASP.NET MVC framework
ASP .net MVC
Asp.Net Mvc
Developing ASP.NET Applications Using the Model View Controller Pattern
Asp.net mvc
ASP.NET MVC introduction
ASP.net MVC CodeCamp Presentation
Mvc interview questions – deep dive jinal desai
Introduction To Mvc
ASP.NET MVC controllers
Introduction to ASP.NET MVC
Asp.Net MVC Framework Design Pattern
CTTDNUG ASP.NET MVC
MVC Training Part 1
Build your web app with asp.net mvc 2 from scratch
MVC & SQL_In_1_Hour
ASP.MVC Training
Chapter4.pptx
Inside asp.net mvc framework
Inside ASP.NET MVC framework
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) { ..... }}