Labels

Monday, April 27, 2009

MVC || Controllers || Understanding Controller Actions Results

Understanding Action Results

 

A controller action returns something called an Action Result.

An action result is what a controller action returns in response to a browser request.

All of these action results inherit from the base ActionResult class.

 

The ASP.NET MVC framework supports several types of action results including:

 

  1. ViewResult – Represents HTML and markup.
  2. EmptyResult – Represents no result.
  3. RedirectResult – Represents a redirection to a new URL.
  4. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
  5. JavaScriptResult – Represents a JavaScript script.
  6. ContentResult – Represents a text result.
  7. FileContentResult – Represents a downloadable file (with the binary content).
  8. FilePathResult – Represents a downloadable file (with a path).
  9. FileStreamResult – Represents a downloadable file (with a file stream).

 

In most cases, a controller action returns a ViewResult. When an action returns a ViewResult, HTML is returned to the browser.

However the ViewResults is not returned directly. Instead, you call one of the following methods of the Controller base class to return the ViewResult.

 

  1. View – Returns a ViewResult action result.
  2. Redirect – Returns a RedirectResult action result.
  3. RedirectToAction – Returns a RedirectToRouteResult action result.
  4. RedirectToRoute – Returns a RedirectToRouteResult action result.
  5. Json – Returns a JsonResult action result.
  6. JavaScriptResult – Returns a JavaScriptResult.
  7. Content – Returns a ContentResult action result.
  8. File – Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.

 

Note - If a controller action returns a result that is not an action result – for example, a date or an integer – then the result is wrapped in a ContentResult automatically. (Line C)

 

 

namespace MvcApplication1.Controllers
{
    public class BookController : Controller
    {
        public ActionResult Index()
        {
            return View();  
            return Content("Hello World!");
            return DateTime.Now;  // Line C
        }
    }
}

 

 

Hope this helps.

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

No comments:

Post a Comment