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.
Here are the names of the return types for a controller action method in ASP.NET MVC or Core.
This is used to return a view to the user.
public IActionResult Index()
{
return View(); // Returns the default view associated with this action.
}
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".
}
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.
}
Returns plain text or any string content.
public IActionResult GetText()
{
return Content("This is plain text."); // Returns plain text content.
}
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.
}
Redirects to a specific URL.
public IActionResult RedirectToGoogle()
{
return Redirect("https://www.google.com"); // Redirects to Google.
}
Redirects to another action method.
public IActionResult RedirectToAbout()
{
return RedirectToAction("About", "Home"); // Redirects to the About action of the Home controller.
}
Returns a 404 Not Found status.
public IActionResult PageNotFound()
{
return NotFound(); // Returns a 404 status.
}
Returns a 400 Bad Request status.
public IActionResult InvalidRequest()
{
return BadRequest("Invalid request."); // Returns a 400 status with a message.
}
Returns a specific HTTP status code.
public IActionResult CustomStatus()
{
return StatusCode(500); // Returns a 500 Internal Server Error status.
}
Represents no result (does nothing).
public IActionResult DoNothing()
{
return new EmptyResult(); // Does nothing.
}