Introduction
In ASP.NET MVC, every controller action method returns a result to the browser. This result tells the MVC framework what response should be sent to the user.
For example:
Show a View page
Return JSON data
Redirect to another page
Return plain text
Return a file download
To handle these situations, ASP.NET MVC provides different Action Result return types.
Understanding when to use each return type is very important for building MVC applications.
What is ActionResult?
ActionResult is the base class for many result types in MVC.
Example:
public ActionResult Index()
{
return View();
}Here the action method returns a ViewResult, but the return type is written as ActionResult.
Why use ActionResult?
Because it allows the method to return different types of results.
Example:
public ActionResult Test()
{
if(true)
return View();
else
return RedirectToAction("Index");
}Types of Return Types in MVC
Below are the most commonly used return types.
| Return Type | Purpose |
|---|---|
| ViewResult | Returns a View page |
| PartialViewResult | Returns Partial View |
| ContentResult | Returns plain text |
| JsonResult | Returns JSON data |
| RedirectResult | Redirects to another URL |
| RedirectToRouteResult | Redirects to another action |
| FileResult | Returns a file |
| EmptyResult | Returns nothing |
1 ViewResult
ViewResult is used to display a View page.
Example Controller:
public ViewResult Index()
{
return View();
}This will open:
Views/Home/Index.cshtmlPassing Data to View
public ActionResult Index()
{
ViewBag.Message = "Welcome to MVC";
return View();
}View:
<h2>@ViewBag.Message</h2>What is this?
Output:
Welcome to MVC2 PartialViewResult
Used to return partial views.
Partial views are small reusable UI components.
Example:
Controller
public PartialViewResult StudentList()
{
return PartialView();
}Partial View file:
_StudentList.cshtmlWhen to Use
AJAX requests
Reusable UI sections
Updating part of a page
3 ContentResult
Used to return simple text content.
Example:
public ContentResult Message()
{
return Content("Hello MVC Developers");
}Output in browser:
Hello MVC DevelopersWhen to Use
Simple text response
Testing APIs
Debugging
4 JsonResult
Used to return JSON data.
Mostly used in AJAX calls.
Example:
Join the conversation! Your thoughts help the community grow.