ASP.NET MVC Controllers & Actions
description
Transcript of ASP.NET MVC 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 pathsreturn View(‘’SubFolder/ViewName’’)return View(‘’~/View.aspx’’)
Returning Redirect Results Same controller
return RedirectToAction(‘’Index’’); Different controller
return RedirectToAction(‘’Product’’, ‘’List’’);
Providing route valuesreturn 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 JavaScriptpublic ActionResult ShowMessage() {
return JavaScript(‘’alert(‘Message!’);’’);}
// View.aspx<%: Ajax.ActionLink(‘’Show message’’, ‘’ShowMessage’’, null) %>
Accessing Request InformationRequest.QueryString RouteData.Route
Request.Form RouteData.Values
Request.Cookies HttpContext.Application
Request.HttpMethod HttpContext.Cache
Request.Headers HttpContext.Session
Request.Url HttpContext.Items
Request.UserHostAddress User
TempData
Action Method Parameters – 1
public ActionResult ShowInfo(string city) {// Equivalent tovar tempCity = Request.Form[‘’city’’];
} Optional Parameters
Nullable typesDefaultValueAttributeOptional Parameters with C# 4.0
Complex Parameterspublic ActionResult Update(Product p) { .... }
Action Method Parameters – 2
Invoking model binding manuallypublic 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 viewspublic ActionResult ProductInfo(int id) {
var product = repository.Get(id);return View(product);
}
// View.aspxProduct Name: <%: Model.Name %>
Passing Data to Views – 3 Passing 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 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
IAuthorizationFilter AuthorizeAttribute
IActionFilter ActionFilterAttribute
IResultFilter ActionFilterAttribute
IExceptionFilter HandleErrorAttribute
Applying Filters
[Authorize(Roles=‘’Administrator’’)]public class ProductController : Controller {
[OutputCache(Duration=30)]
public ActionResult Save(Product p) {
}
}
How Filters are Executedtry{
Run each IAuthorizationFilter's OnAuthorization() methodif(none of the IAuthorizationFilters cancelled execution){
Run each IActionFilter's OnActionExecuting() methodRun the action methodRun each IActionFilter's OnActionExecuted() method (in reverse order)Run each IResultFilter's OnResultExecuting() methodRun the action resultRun each IResultFilter's OnResultExecuted() 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's OnException() methodRun any action result set by the exception filters
}
IActionFilter, IResultFilter Methods
OnActionExecuting() Before the action runs Prevent executionInspect & edit parameters
OnActionExecuted() After the action runs Edit the exceptionChange the result
OnresultExecuting() Before the ActionResult is executed
Inspect ActionResultPrevent execution
OnResultExecuted() After the ActionResult is executed
Obtain exception detailsInspect ActionResult
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 FilterDuration
VaryByParam
VaryByHeader
VaryByCustom
VaryByContentEncoding
Location Server / Client / DownStreamServerAndClient = Server & ClientAny = Server & DownStreamNone
NoStore
CacheProfile
SqlDependency
Order Irrelevant