Introduction and Background
Last week, one of my friends asked the question “Why there is ContentResult data type in the action method and what is its purpose?” I am dedicating this article to him. I hope he will like this.
- What is ActionResult?
- Content Returning Results
- Redirection Results
- Status Results
The first part of the question is: "Why there is ContentResult data type in the action method?". To understand this, you have to understand the data types in ASP.NET MVC 5 because the ContentResult is a data type whose base data type is ActionResult, hence you have to understand Action Result.
Let’s get started with Action Result.
Action Result
Action Result is actually a data type. When it is used with action method, it is called return type. As you know, an action is referred to as a method of the controller, the Action Result is the result of action when it executes. In fact, Action Result is a return type. This return type has many other derived types. First, look at the base and derived types of ActionResult.
- namespace System.Web.Mvc
- {
- public abstract class ActionResult
- {
- //
- // Summary:
- // Initializes a new instance of the System.Web.Mvc.ActionResult class.
- protected ActionResult();
- }
- }
To see inside the assembly, you can either follow the following steps after downloading ILSpy or you can watch this video by clicking here.
- I am giving you the direct link to download the ILSpy. Click here.
- If you don’t have the System.Web.Mvc assembly, then you can download after clicking here.
- Run ILSpy after extracting it.
- Click on File (on the top-left-corner)
- Select “Open” option and open the assembly from where you downloaded it.
- After selecting, the assembly will load in ILSpy software.
- Expand the assembly, you will see ActionResult, expand it also, you will see the base and derived types also.
- The types of ActionResult is shown in the image below:
When we go into ActionResult, we see that it is an abstract class.
- namespace System.Web.Mvc
- {
- public abstract class ActionResult
- {
- //
- // Summary:
- // Initializes a new instance of the System.Web.Mvc.ActionResult class.
- protected ActionResult();
- }
- }
- public ActionResult Index()
- {
- bool answer = DateTime.Now.Day + 2 == 5;
- if (answer)
- {
- return Content("Correct");
- }
- else
- {
- return View();
- }
- }
The above concept also answers the question “When to choose base type ActionResult or derived type?”
Choosing the derived type for a specific result is a good practice, but when you want that your action method should return multiple types, then you have to use base type ActionResult.
Now, the important concept comes. There are three categories for the derived types. Let’s take a look at it.
- Content Returning Results
- Redirection Results
- Status Results
Content Returning Results
As the name depicts these results are used for returning the content to the browser. There are 7 types of content returning results:
- ViewResult
- PartialViewResult
- ContentResult
- EmptyResult
- FileResult
- JsonResult
- JavaScriptResult
ViewResult is a datatype which is responsible for returning the View. Let’s look at its example.
- public class HomeController : Controller
- {
- public ViewResult Index()
- {
- return View();
- }
- }
- <h2>
- This is Index View.
- </h2>
- public class HomeController : Controller
- {
- public ViewResult Index()
- {
- return View(“Second View” );
- }
- }
- <h2>This is Second View but having action name "Index"</h2>
PartialViewResult
It is the type which is used to return the partial view page rather than returning the regular view page. Look at its example.
- public class HomeController : Controller
- {
- public PartialViewResult Index()
- {
- return PartialView("Second View");
- }
- }
- <h2>This is Second View but having action name "Index"</h2>
As you can see the output of PartialViewResult is same as that of ViewResult. But the content of layout page is missing. It is just an example. This is not the real-time example.
Now, let’s look at the example where we’ll see layout page. Make a new controller named as “Student” and an action method named as “Name”, as shown below,
- public class StudentController : Controller
- {
- public PartialViewResult Name()
- {
- return View("_SecondView");
- }
- }
Now, when you execute it, you will see the same output but having content of layout page. See the figure below.
ContentResult
"Content" result is a datatype which is responsible for the returning of content. But the point of interest is, you will have proper control over the returned content. I mean to say that you have to add the content in the “Content” helping method of ContentResult type. Here you can pass the contents like HTML content, Javascript content or any other content. Let’s understand it with examples.
Code of Home controller is given below,
- public class HomeController : Controller
- {
- public ContentResult Index()
- {
- return Content("<h3>Zain Ul Hassan </h3>");
- }
- }
- public class HomeController : Controller
- {
- public ContentResult Index()
- {
- return Content("<h3>Zain Ul Hassan</h3>", "text/html");
- }
- }
- public class HomeController : Controller
- {
- public ContentResult Index()
- {
- return Content(
- "<script> alert('Hi! I am Zain Ul Hassan') </script>"
- );
- }
- }
EmptyResult
This type is genuinely for returning nothing. But the problem is, this EmptyResult type doesn’t have any helper method. So we can use it by making its object, as shown below,
- public class HomeController : Controller
- {
- public EmptyResult Index()
- {
- return new EmptyResult();
- }
- }
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return null;
- }
- }
FileResult
FileResult is a type which is used to return the file to the browser. The helper method for this type is File, and has many overloads. So if we use the following overload and specify only the URL of the file and the MIME (Multipurpose Internet Mail Extensions) type then we should see the content of the file in the browser. Let’s take an example.
The overload we use is,
- protected internal FilePathResult File(string fileName, string contentType);
- public class HomeController : Controller
- {
- public FileResult Index()
- {
- return File("~/Files/text.txt", "text/plain");
- }
- }
- public class HomeController : Controller
- {
- public FileResult Index()
- {
- byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Files/text.txt"));
- return File(fileBytes, "text/plain");
- }
- }
- protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName);
- public class HomeController : Controller
- {
- public FileResult Index()
- {
- return File(Url.Content("~/Files/text.txt"), "text/plain", "testFile.txt");
- }
- }
JsonResult
It is the derived type of ActionResult which is used to represent the JSON data. To see how can we JSONify any data, you can see code below:
- public JsonResult Index()
- {
- return Json(new { Name = "Zain Ul Hassan", ID = 1 });
- }
As you know, JSON contains your encoded data that can be precious, so MVC strictly stops the sharing of information over a GET request. In fact, MVC is trying to prevent you from JSON Hijacking.
So if you want to share the information over the GET request then you have to use the code shown below,
- public JsonResult Index()
- {
- return Json(new { Name = "Zain Ul Hassan", ID = 1 }, JsonRequestBehavior.AllowGet);
- }
JavaScriptResult
This derive type is used for returning the javascript code from the controller. When it executes we see the javascript code as we mentioned in the controller’s action method. For details, let’s take an example,
- public JavaScriptResult Index()
- {
- return JavaScript("alert('Zain Ul hassan')");
- }
- <script type="text/javascript" src="@Url.Action("Index")"></script>
This type of ActionResult is used for redirection purpose, which will you see with examples here. There are 2 types of redirection results,
- RedirectResult
- Redirect to Action Result
If you use this type then it’ll redirect to the URL specified by you. An example is given below,
- public RedirectResult Index()
- {
- return Redirect("https://www.c-sharpcorner.com/members/zain-ul-hassan2");
- }
RedirectionToRouteResult
It is responsible for the redirection to the actions within the application. There are many helper methods in it which are actually overloads. We use RedirectToRoute which redirect us to the action within the specified controller. Let’s look at its example.
- public RedirectToRouteResult Index()
- {
- return RedirectToRoute(new { controller = "Student", action = "Name" });
- }
- <h2>Redirection Successfull</h2>
- public class HomeController : Controller
- {
- public RedirectToRouteResult Index()
- {
- return RedirectToAction("SecondIndex");
- }
- public ActionResult SecondIndex()
- {
- return View();
- }
- }
- <h3>This is the SecondIndex of the same controller named as "Home"</h3>
Status ResultIts responsibility is to give the status code to the browser. There are three types of this set explained below,
- HttpStatusCodeResult
- HttpUnauthorizedResult
- HttpNotFoundResult
This type is used to give HTTP status code to the browser. Look at its example.
- public HttpStatusCodeResult Index()
- {
- return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
- }
- public HttpStatusCodeResult Index()
- {
- return new HttpStatusCodeResult(HttpStatusCode.Unauthorized, "Sorry! You don't have access.");
- }
If you don’t want to use System.Net namespace then HttpStatusCodeResult has an overload whose output will be same as above. See the code below:
- public HttpStatusCodeResult Index()
- {
- return new HttpUnauthorizedResult("Sorry! You don't have access.");
- }
HttpNotFoundResult
- public HttpNotFoundResult Index()
- {
- return HttpNotFound("Sorry! You don't have access.");
- }
These were the basic and foremost things to understand Action Results. If you have any query then feel free to contact me in the comments. Also, give feedback either positive or negative, it will help me to make my articles better and increase my enthusiasm to share my knowledge.
No comments:
Post a Comment