Skip to main content

ASP.NET Core - Action Results

We will discuss the Action Results.
  • This base class gives us access to lots of contextual information about a request, as well as methods that help us build results to send back to the client.
  • You can send back simple strings and integers in a response. You can also send back complex objects like an object to represent a student or university or restaurant etc. and all the data associated with that object.
  • These results are typically encapsulated into an object that implements the IActionResult interface.
  • There are many different result types that implement this interface — result types that can contain models or the contents of a file for download.
  • These different result types can allow us to send back JSON to a client or XML or a view that builds HTML.
Actions basically return different types of Action Results. The ActionResult class is the base for all the action results. The following is a list of different kind of action results and their behavior.
NameBehavior
ContentResultReturns a string
FileContentResultReturns file content
FilePathResultReturns file content
FileStreamResultReturns file content.
EmptyResultReturns nothing
JavaScriptResultReturns script for execution
JsonResultReturns JSON formatted data
RedirectToResultRedirects to the specified URL
HttpUnauthorizedResultReturns 403 HTTP Status code
RedirectToRouteResultRedirect to different action/ different controller action
ViewResultReceived as a response for view engine
PartialViewResultReceived as a response for view engine

Example 1

Let us perform a simple example by opening the HomeController class and derive it from the controller based class. This base class is in the Microsoft.AspNet.Mvc namespace. The following is the implementation of the HomeController class.
using Microsoft.AspNet.Mvc; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;  

namespace FirstAppdemo.Controllers  { 
   public class HomeController : Controller { 
      public ContentResult Index() { 
         return Content("Hello, World! this message is from 
            Home Controller using the Action Result"); 
      } 
   } 
}
You can now see that the index method is returning the ContentResult which is one of the result types and all these result types implement ultimately an interface, which is the ActionResult.
In the Index method, we have passed a string into the Content method. This Content method produces a ContentResult; this means the Index method will now return ContentResult.
Let us save the HomeController class and run the application in the browser. It will produce the following page.
Action Result
You can now see a response which doesn’t look any different from the response we had before. It is still just going to be a plain text response.
  • You might be wondering what is the advantage of using something that produces an ActionResult.
  • The typical advantage is that it is just a formal way to encapsulate the decision of the controller.
  • The controller decides what to do next, either return a string or HTML or return a model object that might be serialized into JSON etc.
  • All that the controller needs to do is make that decision and the controller does not have to write directly into the response the results of its decision.
  • It just needs to return the decision and then it is the framework that will take a result and understand how to transform that result into something that can be sent back over HTTP.

Example 2

Let us take another example. Create a new folder in the project and call it Models. Inside the Models folder, we want to add a class that can represent an Employee.
Models
Enter Employee.cs in the Name field as in the above screenshot. Here, the implementation of the Employee class contains two properties.
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;  

namespace FirstAppDemo.Models { 
   public class Employee { 
      public int ID { get; set; } 
      public string Name { get; set} 
   } 
}
Inside the Index action method of HomeController, we want to return an Employee object. The following is the implementation of HomeController.
using FirstAppDemo.Models; 
using Microsoft.AspNet.Mvc; 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;  

namespace FirstAppdemo.Controllers { 
   public class HomeController : Controller { 
      public ObjectResult Index() { 
         var employee = new Employee { ID = 1, Name = "Mark Upston"}; 
         return new ObjectResult(employee); 
      } 
   } 
} 
Now, instead of returning the Content, we will return a different type of result which is known as ObjectResult. If we want an ObjectResult, we need to create or instantiate an ObjectResult and pass into it some model object.
  • An ObjectResult is special in the MVC framework because when we return an ObjectResult, the MVC framework looks at this object. This object needs to be represented in the HTTP response.
  • This object should be serialized into XML or JSON or some other format and ultimately, the decision will be made based on the configuration information that you give to the MVC at startup. If you don't configure anything, you just get some defaults, and the default is a JSON response.
Save all your files and refresh the browser. You will see the following output.
Mark Upston

Comments

Popular posts from this blog

Scenario : Cloud Computing

ASP.NET Core - MVC Setup

Here we will set up the MVC framework in our FirstAppDemo application. We will proceed by building a web application on top of the ASP.NET Core, and more specifically, the ASP.NET Core MVC framework. We can technically build an entire application using only middleware, but ASP.NET Core MVC gives us the features that we can use to easily create HTML pages and HTTP-based APIs. To setup MVC framework in our empty project, follow these steps − Install the  Microsoft.AspNet.Mvc  package, which gives us access to the assemblies and classes provided by the framework. Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the  ConfigureServices  method. Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write. Step 1  − Let us go to the NuGet package manager by ri

SQL Server Tutorial - Date functions

1. Get month names with month numbers: In this query we will learn about  How to get all month names with month number in SQL Server . I have used this query to bind my dropdownlist with month name and month number. 1 2 3 4 5 6 7 8 9 10 11 12 ;WITH months(MonthNumber) AS (      SELECT 0      UNION ALL      SELECT MonthNumber+1      FROM months      WHERE MonthNumber < 12 ) SELECT DATENAME(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) AS [MonthName],Datepart(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) AS MonthNumber FROM months ORDER BY Datepart(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) ; 2. Get name of current month: In this query we will learn about  How to get name of current month in SQL Server . 1 select DATENAME(MONTH, GETDATE()) AS CurrentMonth 3. Get name of day: In this query we will learn about  How to get name of day in SQL Server . 1 select DATENAME(WEEKDAY, GETDATE()) AS TodayI