Action Results in ASP.NET Core MVC

Action Results in ASP.NET Core MVC

In this article, I am going to give an overview of the Action Results in ASP.NET Core MVC Web Application with Examples. In ASP.NET Core MVC, there are many different types of Action Results. Each action result returns a different format of the output. As a programmer, we need different action results to get the expected output per our business requirements. So, at the end of this article, you will understand the different types of Action Results and when to use which action results in ASP.NET Core MVC Application.

What is the Action Method in ASP.NET Core MVC?

Before understanding Action Results, we first need to understand what action methods are in ASP.NET Core MVC Application. All the public methods inside a Controller which respond to the Incoming URL or HTTP Requests are known as Action Methods. When creating an Action Method, we must follow the below rules.

  • The action method must be public.
  • It cannot be overloaded.
  • It cannot be a static method.
  • ActionResult is the base class of all the result types that an action method returns.
What is the Action Result in ASP.NET Core MVC?

In ASP.NET Core MVC, an action result is an object that represents the result of an action method within a controller. An action method is responsible for processing a client’s request and generating an appropriate response. The action result encapsulates the data and behavior needed to create the response that will be sent back to the client.

Action Result is the return type of an action method in the ASP.NET Core MVC Application. The Action Result is an abstract class. It is the base class for all types that an action method returns. As you can see in the below diagram, View, Partial View, Redirect, Json, Content, File, RedirectToAction, etc., are derived from the abstract Action Result class, and these types can also be used as the return type of an action method.

What is the Action Result in ASP.NET Core MVC?

ActionResult Class in ASP.NET Core:

If you go to the definition of ActionResult class, then you will see the following signature. As you can see in the below image, ActionResult is an Abstract class that is inherited from the I ActionResult interface, and it has one constructor and two methods.

ActionResult Class in ASP.NET Core

The constructor is basically used to initialize a new instance of the ActionResult class. This class has the following two methods.

  • ExecuteResult(ActionContext context): This method executes the result operation of the action method synchronously. MVC calls this method to process the result of an action method. The context is the object in which the result is executed. The context includes information about the action that was executed, such as Controller, HTTP Content, request context, and route data, etc.
  • ExecuteResultAsync(ActionContext context): This method executes the result operation of the action method asynchronously. MVC calls this method to process the result of an action method. The default implementation of this method calls the ExecuteResult method and returns a completed task.
Why is ActionResult an Abstract Class in ASP.NET Core MVC?

This is because different controller action methods can return different types of results as per the business needs, and still, the ASP.NET Core MVC Framework handles them properly. If you mention the return type of an action method as ActionResult, then the action method can return any type which is derived from the ActionResult abstract class.

Types of Action Results in ASP.NET Core MVC

An action method can return many different types of Action Results in ASP.NET MVC. Each Action Result returns a different type of result format. ActionResult is the base class of all the result types. The following are the Result types that an action method can return in ASP.NET MVC Application.

  • ViewResult: Represents HTML and markup. It represents an HTML view that will be rendered and returned to the client’s browser. It allows you to pass a model to the view, which can be used for rendering dynamic content.
  • PartialViewResult: Similar to ViewResult, it’s used for rendering a partial view. A partial view is a smaller, reusable component of a larger view.
  • ContentResult: Represents a raw string content that will be sent as the response to the client. This can be used to return plain text, HTML, JSON, XML, or any other kind of text-based content.
  • JsonResult: Represents a JSON-formatted response. It allows you to return JSON data to the client.
  • RedirectResult: Represents a redirect response to another URL. This can be used to redirect the client’s browser to a different page.
  • RedirectToRoute: This represents a response that redirects to a specific route configured in your application.
  • RedirectToActionResult: A more flexible version of RedirectResult that allows you to specify an action and controller instead of a URL. This is particularly useful when you want to redirect within your application using route information.
  • FileResult: Represents a file download response. You can use it to return files to the client for downloading, such as PDFs, images, etc.
  • NotFoundResult: Represents a 404 Not Found response. It’s used to indicate that the requested resource could not be found.
  • BadRequestResult: Represents a 400 Bad Request response. It indicates that the client’s request was malformed or invalid.
  • StatusCodeResult: This represents a response with a specific HTTP status code. You can use this to return custom status codes and messages.
  • ObjectResult: Represents a response containing an arbitrary object. It’s often used in combination with content negotiation to automatically select the appropriate format (JSON, XML, etc.) based on the client’s preferences.

These action results allow us to customize the response generated by our action methods and provide the appropriate content to the client. You can choose the appropriate action result type based on the desired response and the type of data you want to return.

Many of the derived classes we’re going to discuss have associated helpers. These helpers provide shortcuts to the constructor methods of their related Results. That allows us to write return View() rather than return new ViewResult().

Types of Action Results in ASP.NET Core MVC:

Action results in ASP.NET Core MVC can be categorized into different groups based on their functionality and the type of response they generate. Here’s a categorized breakdown of the various action results:

View Results:

View Results in ASP.NET Core MVC are action results used to render and return HTML views to the client’s browser. They are responsible for generating the HTML content that the user sees in their web browser. View results allow you to combine dynamic data with HTML templates and create dynamic web pages. There are two main types of View Results in ASP.NET Core MVC:

  • ViewResult: This is the most common type of View Result. It represents a full HTML view that will be rendered and returned to the client. It uses the Razor view engine to render dynamic content. You can pass a model to the view, which the view can use to generate dynamic content.
  • PartialViewResult: A PartialViewResult represents a partial view, which is a reusable component of a larger view. Partial views can be rendered within other views or partial views, allowing you to create modular and reusable UI components.

Both ViewResult and PartialViewResult are essential for creating dynamic and interactive web applications in ASP.NET Core MVC. They allow you to separate your presentation logic from your business logic, making your code more maintainable and allowing for a better user experience.

Content Results:

Content Results in ASP.NET Core MVC are action results that allow us to return raw content directly to the client’s browser as a response. This raw content can be in various formats, such as plain text, HTML, JSON, XML, or any other format, or even downloadable files like CSV or XML. Content Results are particularly useful when you need to return non-HTML data or when you want more control over the exact content that is sent to the client.

There are three main types of Content Results in ASP.NET Core MVC:

  • ContentResult: Represents a response containing raw text-based content. It allows you to specify the content, content type, and encoding that will be sent to the client.
  • JsonResult: Represents a response containing JSON-formatted content. It’s specifically designed for returning JSON data to the client.
  • FileResult: Represents a file download response. Used to send files to the client for downloading, such as PDFs, images, etc.

Content Results are useful when you want to send specific content, such as API responses, custom data formats, or even downloadable files like CSV or XML. They offer fine-grained control over the response’s content and headers, enabling you to craft responses that suit your application’s needs.

Redirect Results:

Redirect Results in ASP.NET Core MVC are a type of action result that instructs the client’s browser to navigate to a different URL or action within the application. They are used when you need to perform a redirection, such as after a form submission or when handling authentication.

There are three main types of Redirect Results in ASP.NET Core MVC:

  • RedirectResult: This represents a response that instructs the client’s browser to redirect to a different URL outside the application.
  • RedirectToRoute: This represents a response that redirects to a specific route configured in your application.
  • RedirectToActionResult: Represents a response that redirects to a specific action and controller within the application.

Redirect Results are commonly used for scenarios like post-redirect-get (PRG) patterns, where a form submission is followed by a redirection to prevent duplicate form submissions. They are also used for implementing authentication flows, processing data, and handling various user interactions in your application. By using Redirect Results, you can provide a smooth user experience and ensure proper navigation within your application or to external resources.

Status Results:

Status Results in ASP.NET Core MVC are action results that allow you to return HTTP status codes along with optional content. They are used to indicate the outcome of an operation or to communicate the current state of the server’s response to the client.

There are several types of Status Results in ASP.NET Core MVC:

  • StatusCodeResult: This represents a response with a specific HTTP status code and no additional content.
  • NotFoundResult: This represents a response with the HTTP status code 404 (Not Found).
  • BadRequestResult: Represents a response with the HTTP status code 400 (Bad Request).
  • OkResult: Represents a response with the HTTP status code 200 (OK).

Status Results are useful when you want to communicate the outcome of an operation without providing additional content in the response body. They are commonly used for indicating success, failure, or various error conditions to the client. By using Status Results, you can ensure that the client understands the result of their request based on the provided HTTP status code.

Object Result:

Object Results in ASP.NET Core MVC are action results that allow you to return arbitrary objects as responses. These objects can be of various types, such as custom classes, built-in types, or collections. Object Results are useful when you want to return data in a format that can be automatically serialized into different content types (e.g., JSON, XML) based on the client’s preferences.

  • ObjectResult: Represents a response containing an arbitrary object. It’s often used with content negotiation to automatically select the appropriate format based on the client’s preferences.

Object Results are versatile because they allow you to return various types of data in a format that suits the client’s requirements. They are commonly used in APIs to provide responses containing data objects, making it easy to build APIs that can serve multiple content types without duplicating logic for each content type.

These categorized action results help you manage and customize the responses generated by your action methods. By choosing the appropriate action result type, you can ensure that your application responds to client requests in the desired manner and provides the necessary content.

What Should Be the Return Type of an Action Method – Action Result or Specific Derived Type?

In ASP.NET Core MVC, you have the flexibility to choose between using the ActionResult base class or specific derived types as the return type for your action methods. Both approaches have their advantages and use cases. Let’s explore the considerations for each option:

Using ActionResult Base Class:

When you use the ActionResult base class, you’re indicating that the specific type of action result will be determined dynamically based on context, content negotiation, and other factors. This approach offers greater flexibility in changing the response type based on different scenarios.

If your action method returns different kinds of results based on different conditions, then you should use ActionResult as the return type. For a better understanding, please look at the example code below. As the Index method returns two types of Results, i.e., View Result and Json Result, we are using the Action method’s return type as ActionResult.

Action Results in the ASP.NET Core MVC

Advantages:
  • Flexible content negotiation: You can easily switch between different types of action results based on client preferences.
  • Easily handle multiple response types for the same action method.
Using Specific Derived Types:

With this approach, you explicitly define the return type of your action method as a specific derived type like ViewResult, JsonResult, RedirectResult, etc. This approach can provide more clarity and improve readability by making it explicit what type of response the action method will produce.

In the example below, the action method will return one type of result, i.e., JsonResult, so it is advisable to use JsonResult as the action method’s return type.

Action Results in the ASP.NET Core MVC

Advantages:
  • Clear and explicit indication of the expected response type.
  • Less room for ambiguity in the code.
Choosing Between Action Result and Specific Derived Type:
  1. If your action method primarily returns a single, consistent type of response (e.g., always returns JSON data, always returns a view), using specific derived types can provide clarity and make the code more self-explanatory.
  2. If your action method needs to handle multiple types of responses based on different conditions or requirements, using the ActionResult base class allows you to choose the appropriate response type dynamically.

In many cases, a mix of both approaches can be beneficial. Use specific derived types when the response type is consistent, and use ActionResult when the response type varies based on runtime conditions or client preferences. Ultimately, the choice depends on your application’s design, flexibility, and coding preferences.

IActionResult and ActionResult in ASP.NET Core MVC:

In ASP.NET Core MVC, IActionResult and ActionResult are fundamental concepts for returning responses from action methods within controllers. Let’s explore what each of these terms means and how they relate to each other:

IActionResult:
  • IActionResult is an interface provided by the ASP.NET Core MVC framework that represents the result of an action method. It serves as a contract for different types of action results that can be returned from an action method. By returning an IActionResult, you indicate that your action method can produce a variety of possible responses, including views, files, JSON data, redirects, and more.
  • Using IActionResult provides a high degree of flexibility because you can dynamically choose the appropriate action result type based on runtime conditions, client preferences, or other factors.
ActionResult:
  • ActionResult is an abstract base class that implements the IActionResult interface. It’s designed to be a convenient way to return various types of action results without explicitly specifying the derived result type. It’s especially useful when you want to return different types of results within the same action method based on different scenarios.
  • By returning ActionResult, you allow the framework to determine the appropriate derived type of action result based on the context and content negotiation.

Both IActionResult and ActionResult are crucial concepts for building flexible and versatile action methods in ASP.NET Core MVC. The choice of whether to use one or the other depends on your specific scenario and coding preferences.

Differences Between IActionResult and ActionResult in ASP.NET Core MVC:

IActionResult and ActionResult are related concepts in ASP.NET Core MVC that both deal with returning responses from action methods, but they have distinct differences in how they are used. Let’s highlight the main differences between IActionResult and ActionResult:

Interface vs. Abstract Class:
  • IActionResult: An interface provided by ASP.NET Core MVC defines a contract for different types of action results. It doesn’t provide any implementation details but requires implementing classes to define methods for generating responses.
  • ActionResult: It’s an abstract base class that implements the IActionResult interface. It provides a convenient way to return various types of action results without explicitly specifying the derived result type.
Explicit vs. Dynamic Return Types:
  • IActionResult: By using IActionResult, you indicate that the return type of your action method can be any type that implements the IActionResult interface. This allows you to choose the appropriate response type dynamically based on conditions or content negotiation.
  • ActionResult: When using ActionResult, you’re relying on the framework to determine the appropriate derived result type based on the context. It provides a more concise way to return results without specifying the exact derived type.
Usage Clarity:
  • IActionResult: Using IActionResult allows for more explicit signaling that the action method can return various types of responses. This can be helpful in cases where you want to highlight the flexibility of your action method’s responses.
  • ActionResult: Using ActionResult can provide a more streamlined and concise code structure, especially when you have scenarios where you switch between different types of responses based on conditions.
Commonalities:
  • Both IActionResult and ActionResult are used to return responses from action methods in ASP.NET Core MVC.
  • Both allow you to return views, partial views, content, JSON data, redirects, and other types of responses.
  • Both contribute to the flexibility and versatility of your action methods.

In Real-Time Application, you can choose either approach based on your preferences and the requirements of your application. IActionResult is more explicit and allows for greater flexibility, while ActionResult simplifies the code by allowing the framework to determine the appropriate response type. It’s common to see a mix of both approaches within an ASP.NET Core MVC application.

Why Action Results in ASP.NET Core MVC?

Action Results in ASP.NET Core MVC serve as the mechanism by which action methods within controllers generate and return responses to client requests. They play a crucial role in shaping the behavior and output of your web application. Here are the primary reasons why action results are used in ASP.NET Core MVC:

  • Response Generation: Action results enable you to generate and customize the content that will be sent back to the client’s browser. Whether it’s HTML views, JSON data, plain text, or other types of responses, action results provide the means to create the appropriate output based on the request.
  • Decoupling Logic: Action results help in separating the business logic from the presentation logic. This separation of concerns is a key principle of MVC architecture. Returning action results keeps the logic for processing data separate from the logic for generating responses.
  • Content Negotiation: Action results support content negotiation, allowing you to return the same data in different formats (e.g., JSON, XML) based on the client’s preferences. This is particularly useful for building APIs that can serve multiple clients with different content requirements.
  • Flexibility: ASP.NET Core MVC provides a wide range of action result types, each designed for specific use cases. Whether you need to render views, return files for download, perform redirects, or send JSON data, an appropriate action result type is available.
  • Error Handling: Action results are used to communicate the status and outcome of an action. By returning different status codes (such as 404 for “Not Found” or 500 for “Internal Server Error”), you can indicate to the client whether the operation was successful or encountered an issue.
  • Consistent API Design: When building APIs, action results help in maintaining a consistent response structure. You can use common result types like BadRequest, NotFound, and Ok to create a uniform API experience.
  • PRG Pattern: Action results are essential for implementing the Post-Redirect-Get (PRG) pattern. After handling a form submission, using a redirected result helps prevent duplicate form submissions when users refresh the page.
  • User Experience: Different action result types contribute to creating a seamless and user-friendly experience. For example, using RedirectToAction helps users navigate to different parts of your application while returning JSON data can power dynamic client-side interactions.

In summary, action results in ASP.NET Core MVC enable you to craft and manage the responses your application sends to clients. They promote code organization, flexibility, and a consistent approach to handling different types of responses, making your application more maintainable and user-friendly.

How to Use Action Results in ASP.NET Core MVC?

Using action results in ASP.NET Core MVC is fundamental to building web applications. Action results allow you to generate and return various types of responses from your action methods within controllers. Here’s a step-by-step guide on how to use action results in ASP.NET Core MVC:

Create a Controller:

Start by creating a controller that contains the action methods where you’ll be using action results. You can create a new controller by right-clicking on the “Controllers” folder, selecting “Add” > “Controller,” and choosing the appropriate template (e.g., “MVC Controller – Empty”).

Define Action Methods:

Within your controller, define action methods that correspond to different routes and functionalities in your application. These methods will return action results based on the type of response you want to send.

Return Action Results:

Use the appropriate action result type to generate and return the desired response in your action methods. Here are some common action result types you can use:

  • ViewResult: Used to render and return a view.
  • PartialViewResult: Used to render and return a partial view.
  • ContentResult: Used to return raw content (e.g., plain text, HTML, JSON).
  • JsonResult: Used to return JSON-formatted data.
  • FileResult: Used to return a file for download.
  • RedirectResult / RedirectToActionResult: Used to perform redirects.

Here’s an example of using a ViewResult:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
Pass Data to Views (Optional):

Suppose you’re using view results like ViewResult or PartialViewResult. In that case, you can pass data to your views by including a model parameter in the action method and returning the model along with the view result.

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            var homeIndexViewModel = new HomeIndexViewModel()
            {
                Id = 1,
                Name = "Home",
            };
            return View(homeIndexViewModel);
        }
    }
    public class HomeIndexViewModel
    {
        public int Id { get; set; }
        public string? Name { get; set; }
    }
}
Handle Different Scenarios:

Use different action results based on different scenarios and requirements. For example, return a NotFoundResult when a resource is not found or return a JsonResult when you need to provide data for an API response.

Content Negotiation (Optional):

If you’re building APIs, leverage content negotiation to automatically determine the appropriate response format (JSON, XML) based on the client’s request. Use the ObjectResult class with the Produces attribute to achieve this.

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    [Produces("application/json")]
    public class ApiController : Controller
    {
        public IActionResult Get()
        {
            var data = new SomeModel()
            {
                Id = 1,
                Name = "Home",
            };

            return new ObjectResult(data);
        }
    }

    public class SomeModel
    {
        public int Id { get; set; }
        public string? Name { get; set; }
    }
}
Test and Verify:

Test your action methods by navigating to the corresponding URLs in your web browser or using tools like Postman for APIs. Make sure the responses match your expectations.

Handle Errors and Edge Cases:

Use appropriate action results to handle errors, invalid inputs, and edge cases. Return BadRequestResult, NotFoundResult, or custom status codes based on the situation.

By understanding the various action result types and how to use them, you can effectively create dynamic, interactive, and user-friendly web applications using ASP.NET Core MVC.

In the next article, I am going to discuss View Results in ASP.NET Core MVC Application. In this article, I try to give an overview of Action Results in the ASP.NET Core MVC application. I hope you enjoy this Action Result in the ASP.NET Core article.

Leave a Reply

Your email address will not be published. Required fields are marked *