SlideShare a Scribd company logo
Controllers & Actions in MVCEyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.eVardi.com
AgendaControllers OverviewViewData vs. ViewBagAction & ActionResultController AttributesAsync Controller
Understanding ControllersMVC controllers are responsible for responding to requests made against an ASP.NET MVC website.
The Controller  ResponsibilityExecute the right action method and validating that it can be called.Getting the values to use as the action method's arguments.Handling all errors that might occur during the execution of the action method.Providing the default WebFormViewEngineclass for rendering ASP.NET page types (views).
Controller Samplehttp://E4D.co.il / Course / Net / MVC /http://E4D.co.il / Course/ Net ? name=MVCpublic class CourseController : Controller{   public ActionResult Net( string name )   {       var course = BL.GetCourse(name);       return View( course );   }}
ViewData PropertyUsed to set view-specific data in a dictionary object that can hold multiple name/value pairs.public class CourseController : Controller{   public ActionResult Net( string name )   {       ViewData["Course"] = BL.GetCourse(name);       return View();   }}
ViewBag PropertyUsed to set view-specific data in a dictionary object that can hold multiple name/value pairs.public class CourseController : Controller{   public ActionResult Net( string name )   {       ViewBag.Course = BL.GetCourse(name);       return View();   }}
ActionsAction == MethodAction must meet certain requirements:Must be public.Cannot be a static method.Cannot be an extension method. Cannot have open generic types.The method is not a method of the controller base class.The method cannot contain ref or out parameters.
Preventing an Action to InvokePrevent the method from being invoked by using the [NonAction] attribute. public class HomeController : Controller{    [NonAction]    public string CompanySecrets()    {        return "This information is secret.";    }    ...}
Action ResultsA controller action returns something called an action result.Action results types:ViewResultEmptyResultRedirectResultJsonResultJavaScriptResultContentResultFileContentResultFilePathResultFileStreamResultHttpNotFoundResultHttpRedirectResultHttpStatusCodeResult
Controller “View” MethodsNormally, you do not return an action result directly. Instead, you call one of the following methods of the Controller base class.
Controller “View”Methods
Controller Class
Controller Attributes[ChildActionOnly][SessionState][OutputCache][ActionName][NonAction][AcceptVerbs][HttpGet][HttpPost][HttpPut][HttpDelete]
SessionState AttributeUsing the attribute, you can completely turn on or off session state, adjust it to read-only, or make it required.Default,  Required,  ReadOnly & Disabled.[SessionState( SessionStateBehavior.Disabled )]public class HomeController : Controller     {   public ActionResult Index()   {       Session["E4D"] = "E4D Learning";                   return View();   }     }
OutputCacheAttribute[ChildActionOnly][OutputCache( Duration = 20 )]public ActionResult CurrentTime()         {    return PartialView();         }<h2>OutputCache Sample</h2> View Time: @DateTime.Now.ToString("h:mm:ss")<br /> Partial View Time: @{    Html.RenderAction("CurrentTime");}
Async ControllerThe AsyncControllerclass enables you to write asynchronous action methods.
Async Actionpublic class PortalController : AsyncController{     [AsyncTimeout(Duration = 5000 )]    publicvoidNewsAsync(string city)     { AsyncManager.OutstandingOperations.Increment(); NewsServicenewsService = newNewsService(); newsService.GetHeadlinesCompleted+= (sender, e) =>         { AsyncManager.Parameters["headlines"] = e.Value; AsyncManager.OutstandingOperations.Decrement();         }; newsService.GetHeadlinesAsync(city);     }      public ActionResult NewsCompleted(NewsHeadline[] headlines)     {    return View( "News",                  new ViewStringModel { Headlines = headlines } );     }}Async Action
Async Action

More Related Content

Controllers & actions

Editor's Notes

  1. http://davidhayden.com/blog/dave/archive/2011/02/09/SessionLessControllersMvc3.aspx
  2. http://davidhayden.com/blog/dave/archive/2011/01/25/PartialPageOutputCachingASPNETMVC3.aspx