MVC- Action Method Return Types


A controller action method in ASP.NET MVC or ASP.NET Core can return various types of results based on the requirement. Below are the common return types with examples and full code.

MVC Return Type

Here are the names of the return types for a controller action method in ASP.NET MVC or Core.

  1. ViewResult
  2. PartialViewResult
  3. JsonResult
  4. ContentResult
  5. FileResult
  6. RedirectResult
  7. RedirectToActionResult
  8. NotFoundResult
  9. BadRequestResult
  10. StatusCodeResult
  11. EmptyResult

1. ViewResult

This is used to return a view to the user.

public IActionResult Index()
{
    return View(); // Returns the default view associated with this action.
}

2. PartialViewResult

Returns a partial view, often used for rendering parts of a web page.

public IActionResult LoadPartial()
{
    return PartialView("_PartialView"); // Returns a partial view named "_PartialView".
}

3. JsonResult

Returns JSON data, typically used in APIs or AJAX requests.

public IActionResult GetJsonData()
{
    var data = new { Name = "John Doe", Age = 30 };
    return Json(data); // Returns JSON-encoded data.
}

4. ContentResult

Returns plain text or any string content.

public IActionResult GetText()
{
    return Content("This is plain text."); // Returns plain text content.
}

5. FileResult

Returns a file for download or display.

public IActionResult DownloadFile()
{
    var fileBytes = System.IO.File.ReadAllBytes("example.pdf");
    return File(fileBytes, "application/pdf", "example.pdf"); // Returns a file for download.
}

6. RedirectResult

Redirects to a specific URL.

public IActionResult RedirectToGoogle()
{
    return Redirect("https://www.google.com"); // Redirects to Google.
}

7. RedirectToActionResult

Redirects to another action method.

public IActionResult RedirectToAbout()
{
    return RedirectToAction("About", "Home"); // Redirects to the About action of the Home controller.
}

8. NotFoundResult

Returns a 404 Not Found status.

public IActionResult PageNotFound()
{
    return NotFound(); // Returns a 404 status.
}

9. BadRequestResult

Returns a 400 Bad Request status.

public IActionResult InvalidRequest()
{
    return BadRequest("Invalid request."); // Returns a 400 status with a message.
}

10. StatusCodeResult

Returns a specific HTTP status code.

public IActionResult CustomStatus()
{
    return StatusCode(500); // Returns a 500 Internal Server Error status.
}

11. EmptyResult

Represents no result (does nothing).

public IActionResult DoNothing()
{
    return new EmptyResult(); // Does nothing.
}

Next