ActionResult types in Asp.net MVC

Controller actions returns the ActionResult and it's possible to return kinds of results based on what we want in the output , let’s consider for types of result in by example in this article.

ActionResult: it just Initializes a new instance of the ActionResult class. ActionResult is the base class for other types of action.

  1.         //Action Result
  2.         public ActionResult Index()
  3.         {
  4.             return Content("this is the route of the application defined in Gloabal.asax");
  5.         }
  6.  
  7.         public ActionResult ActionResult()
  8.         {
  9.             return View();
  10.         }
  11.  
  12.         //returns a hard coded content
  13.         public ActionResult ActionResult2()
  14.         {
  15.             return Content("this is the content of ActionResult, you can return any text by using it!");
  16.         }
  17.  
  18.         //returns to another action
  19.         public ActionResult ActionResult3()
  20.         {
  21.             return RedirectToAction("ActionResult2");
  22.         }
  23.  
  24.         //returns to the Route acion
  25.         public ActionResult ActionResult4()
  26.         {
  27.             return RedirectToRoute("Index");
  28.         }
  29.  
  30.         public ActionResult ActionResult5()
  31.         {
  32.             return File("Silverlight.js", "text/javascript");
  33.         }

ViewResult: It returned as a controller action and Renders a specified view to the response stream

  1.         //View Result
  2.         public ViewResult ViewResult(string name)
  3.         {
  4.             if (name == null) throw new ArgumentNullException("name");
  5.             name = "Ehsan";
  6.             return View("ViewResult", name);
  7.         }

 PartialViewResult: renders a specified partial view to the response stream

  1.         public ActionResult PartialViewResult()
  2.         {
  3.             return PartialView("PartialView");
  4.         }
  5.  
  6.         public PartialViewResult PostMyForm(SampleModel model)
  7.         {
  8.             if (ModelState.IsValid)
  9.             {
  10.                 //TODO:  something with model data
  11.             }
  12.             return PartialView("_UserPartialView", model);
  13.         }
  14.  

ContentResult: The content result lets you define whatever content you wish to return. You can just use the ContentResult to return a plain string , Writes content to the response stream without requiring a view

  1.         public ContentResult ContentResult()
  2.         {
  3.             return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
  4.         }
  5.  
  6.         public ContentResult ContentResult2()
  7.         {
  8.             string fileName =
  9.             Server.MapPath(@"~\Content\Ehsan.xml");
  10.             TextReader tr = new StreamReader(fileName);
  11.             string contents = tr.ReadToEnd();
  12.             return Content(contents, "text/xml");
  13.         }

 EmptyResult:  it just returns An empty response

  1.        public ActionResult StalemateResult()    
  2.        {
  3.             return new EmptyResult();
  4.        }

FileResult: It used to send files as the response. And in the case of sending the file by name you should use FilePathResult

  1.         public FileStreamResult GetFile()
  2.         {
  3.             const string name = "Ehsan.txt";
  4.             var info = new FileInfo(name);
  5.             if (!info.Exists)
  6.             {
  7.                 using (var writer = info.CreateText())
  8.                 {
  9.                    //Do somthings
  10.                 }
  11.             }
  12.             return File(info.OpenRead(), "text/plain");
  13.         }
  14.  

 HttpNotFoundResult: it's the same 404 not found error

  1.         //HttpNotFound
  2.         public ActionResult Details(int id)
  3.         {
  4.             var somthing = "get somthing from repository!";
  5.             if (somthing == null)
  6.             {
  7.                 return new HttpNotFoundResult("Sorry, Not Found");
  8.             }
  9.             else
  10.             {
  11.                 return View("Details");
  12.             }
  13.         }

HttpUnauthorizedResult: 401 Error

  1.         public new void OnAuthorization(AuthorizationContext filterContext)
  2.         {
  3.             if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
  4.             {
  5.                 filterContext.Result = new HttpUnauthorizedResult();
  6.             }
  7.             else
  8.             {
  9.                 //do somthing else
  10.             }
  11.         }

JavaScriptResult: It used to return a java script by action! it has the ContentType hardcoded to "application/x-javascript" and just writes out the Script property.

  1.         public JavaScriptResult JavaScriptResult(ControllerContext context)
  2.         {
  3.             HttpResponseBase response = context.HttpContext.Response;
  4.             response.ContentType = "application/x-javascript";
  5.             return View();
  6.         }
  7.  
  8.         public JavaScriptResult TestJavaScript()
  9.         {
  10.             string s = "$('#divResultText').html('JavaScript Passed');";
  11.             return JavaScript(s);
  12.         }

JsonResult: it uses a hardcoded JavaScriptSerializer to serialize the JSON data

  1.         public JsonResult JsonResult()
  2.         {
  3.             return Json("this will be downloaded if you wait a sec!", JsonRequestBehavior.AllowGet);
  4.         }
  5.  
  6.         public ActionResult JsonResult2(Guid roleId)
  7.         {
  8.             var actions = Enumerable.Range(1, 5).Select(x => x.ToString(CultureInfo.InvariantCulture)).ToList();
  9.             return Json(actions);
  10.         }
  11.  
  12.         public JsonResult JsonResult3()
  13.         {
  14.             var lists = new List<ListItem>() {
  15.         
  16.              new ListItem() { Value = "2", Text = "NONONO" },
  17.              new ListItem() { Value = "3", Text = "YESYESYES" }
  18.          };
  19.             return Json(lists);
  20.         }

RedirectToResult: Performs an HTTP redirection to a specifed URL

  1.         public ActionResult Index()
  2.         {
  3.                return Redirect("http://www.google.com");
  4.         }
  5.  

 RedirectToRouteResult: Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

  1.         public override void OnActionExecuting(ActionExecutingContext filterContext)
  2.         {
  3.             base.OnActionExecuting(filterContext);
  4.  
  5.             if (!UserIsAuthenticated())
  6.             {
  7.                 // Redirect to login page
  8.                 filterContext.Result = new RedirectToRouteResult(
  9.                     new RouteValueDictionary
  10.                     {
  11.                         { "controller", "Login" }
  12.                     });
  13.             }
  14.         }

 FilePathResult: Returns a file to the client

  1.         public ActionResult FilePathResult()
  2.         {
  3.             foreach (string upload in Request.Files)
  4.             {
  5.                 string path = AppDomain.CurrentDomain.BaseDirectory + "Images/";
  6.                 string filename = Path.GetFileName(Request.Files[upload].FileName);
  7.                 Request.Files[upload].SaveAs(Path.Combine(path, filename));
  8.             }
  9.             return View();
  10.         }

 


Tags: C# Asp.Net MVC


comments powered by Disqus