Skip to main content

MVC Controller - Action Results

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.

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

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

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

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.

Example:

    public class ActionResultController : Controller
    {
        public ViewResult ViewResultExample()
        {
            return View();
        }

        public EmptyResult EmptyResultExample()
        {
            return new EmptyResult();
        }

        public ActionResult RedirectResultExample()
        {
            //return Redirect("ViewResultExample");
            return RedirectPermanent("ViewResultExample"); //301
        }

        public JsonResult JsonResultExample()
        {
            return Json(DataRecords.GetData(),JsonRequestBehavior.AllowGet);
        }

        public JavaScriptResult JavaScriptResultExample()
        {
            return JavaScript("<script>alert('hello world');</script>");
        }

        public ContentResult ContentResultExample()
        {
            return Content("<script>alert('hello world');</script>");
        }

        public FileContentResult FileContentResultExample()
        {
            string fileName = "example.txt";
            string fileData = "some data in file";

            var mimeType = "application/text";

            byte[] fileContent = Encoding.ASCII.GetBytes(fileData);
            return File(fileContent, mimeType, fileName);
        }
    }