Skip to main content

MVC – Action Result Methods

  MVC – Action Result Methods

Action Method
·         All the public methods of a Controller class are called Action methods. They are like any other normal methods with the following restrictions:
o    Action method must be public. It cannot be private or protected
o    Action method cannot be overloaded
o    Action method cannot be a static method.
Default Action Method:
·         Every controller can have default action method as per configured route in RouteConfig class. By default, Index is a default action method for any controller, as per configured default root as shown below.
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}/{name}",
    defaults: new { controller = "Home",
                    action = "Index",
                    id = UrlParameter.Optional
            });

ActionResult
·         MVC framework includes various result classes, which can be return from an action method. There result classes represent different types of responses such as html, file, string, json, JavaScript etc. The following table lists all the result classes available in ASP.NET MVC.
Result Class
Description
ViewResult
Represents HTML and markup. Renders a specified view to the response stream
EmptyResult
Represents No response. An empty response is returned
ContentResult
Represents string literal. Writes content to the response stream without requiring a view
FileContentResult/ FilePathResult/ FileStreamResult
Represents the content of a file. Returns a file to the client. Returns a file to the client, which is provided by a Stream. Returns a file to the client
JavaScriptResult
Represent a JavaScript script. Returns a piece of JavaScript code that can be executed on the client
JsonResult
Represent JSON that can be used in AJAX. Serializes a given object to JSON format
RedirectResult
Represents a redirection to a new URL. Performs an HTTP redirection to a specified URL
RedirectToRouteResult
Represent another action of same or other controller. Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
PartialViewResult
Returns HTML from Partial view. Renders a specified partial view to the response stream
HttpUnauthorizedResult
Returns HTTP 403 status

·         The ActionResult class is a base class of all the above result classes, so it can be return type of action methods which returns any type of result listed above. However, you can specify appropriate result class as a return type of action method.

Result Class
Description
Base Controller method
ViewResult
Represents HTML and markup.
View()
EmptyResult
Represents No response.
ContentResult
Represents string literal.
Content()
FileContentResult,
FilePathResult,
FileStreamResult
Represents the content of a file
File()
JavaScriptResult
Represent a JavaScript script.
JavaScript()
JsonResult
Represent JSON that can be used in AJAX
Json()
RedirectResult
Represents a redirection to a new URL
Redirect()
RedirectToRouteResult
Represent another action of same or other controller
RedirectToRoute()
PartialViewResult
Returns HTML
PartialView()
HttpUnauthorizedResult
Returns HTTP 403 status

·         Any action in an MVC controller, generally speaking, returns an ActionResult. Obviously that class represents an action of some kind.

public ActionResult Index()
{
return View();
}

·         An ActionResult in asp.net mvc is an Abstract class and ActionResult is return type of controller method. The class itself inherits from System.Object, and only adds one additional abstract method: ExecuteResult, which is an abstract method that the derived classes of ActionResult will implement themselves.
·         Each ActionResult return different type of result. If we want to display image in WebForms we need to create Imagehandler for it but in Asp.net MVC we can use FileResult which is already built in method.






Types of Action Results in ASP.NET MVC

·         ViewResult
o    ViewResult returns a view.

public class HomeController : Controller
{
public ViewResult Index()
{
return View();
}
}

o    Since MVC follows convention-over-configuration, MVC will look for a View named "Index" in the Views/Home subfolder, and then look in Views/Shared if it doesn't find it (and will throw an InvalidOperationException if it can't find it at all).

·         PartialViewResult
o    We can also specify an action to return a partial view instead of a regular view. It returns a partial view to the response.

public PartialViewResult Partial()
{
return PartialView("LoginPartial");
}

·         FileResult
o    If we want to return a file, this is the ActionResult we use. Depending on which overload we pick, we can specify what action the browser is to take with the downloaded file. For example, if we just specify a URL and a MIME type, the browser attempts to display the file specified. It returns binary file content to the response.

public FileResult ViewFile()
{
return File(Url.Content("~/Files/testfile.txt"), "text/plain");
}

o    Another overload will specify a download name, and using this overload causes the browser to download the file, rather than just display it

public FileResult DownloadFile()
{
return File(Url.Content("~/Files/testfile.txt"), "text/plain", "testFile.txt");
}

·         ContentResult
o    ContentResult is used when we want to allow the action to specify what should be returned. It's a sort of catchall for scenarios where we need to allow the action full control over the returned content. All we need to do is specify the content and MIME type.

public ContentResult Content()
{
return Content("<h3>Here's a custom content header</h3>", "text/html");
}

o    Calling this action will display the h3 tag in the browser.



public string Content()
{
return "<h3>Here's a custom content header</h3>";
}

o    MVC actually creates a ContentResult and wraps it around the returned value (and it doesn't have to be a string). Unless you return null, in which case MVC returns an EmptyResult.

·         EmptyResult
o    MVC wants you to use EmptyResult when the action is specifically intended to return nothing. Unlike all of the previous ActionResults though, EmptyResult doesn't have a helper. Additionally, if an action returns null, MVC will detect that and make it return an EmptyResult.

public EmptyResult Empty()
{
return new EmptyResult();
}

public ActionResult NothingReturned()
{
return null; //Returns an EmptyResult
}

·         JsonResult
o    JsonResult is used to represent JSON-encoded data, which is most commonly used to return structured data to a calling script, especially in AJAX scenarios.
public JsonResult Json()
{
return Json(new { Name = "John Smith", ID = 4, DateOfBirth = new DateTime(1999, 12, 31) });
}

o    That returns a JSON structure that looks like this:
§  {"Name":"John Smith","ID":4,"DateOfBirth":"\/Date(946623600000)\/"}
o    Problems with JSON dates aside, the implications of this are staggering. Since that just encoded an anonymous object, it follows that JsonResult can handle any object, including user-defined ones, and encode them into the JSON format.

public JsonResult Json()
{
return Json(new { Name = "John Smith", ID = 4, DateOfBirth = new DateTime(1999, 12, 31) }, JsonRequestBehavior.AllowGet);
}

o    JsonRequestBehavior.AllowGet does exactly what it sounds like; it allows browsers to access this JSON information in a GET request. I'd only recommend turning this on if you know what you are doing, since it could potentially expose you to JSON Hijacking.

·         JavaScriptResult
o    Another potentially dangerous ActionResult is the JavaScriptResult, which returns script that is to be executed by the browser.

public JavaScriptResult LoadScript()
{
return JavaScript("alert('Hello!  This popup shows that we can return JavaScript from controller actions.')");
}

·         RedirectResult
o    If we want to redirect to a URL, then we can use RedirectResult
o    That works great for redirecting to outside sites from the current app, but not so much for redirecting to other pages within the same app. For that, we can use RedirectToRouteResult.

public RedirectResult RedirectToOtherSite()
{
return Redirect("http://www.google.com");
}

·         RedirectToRouteResult
o    RedirectToRouteResult is used whenever we need to go from one action to another. There are two different ways of using it. One is to create your own Route values using RedirectToRoute:

public RedirectToRouteResult RedirectToRoute()
{
return RedirectToRoute(new { controller = "Home", action = "Route" });
}

public RedirectToRouteResult RedirectToAction()
{
return RedirectToAction("Action");
}

o    RedirectToAction follows the same convention-over-configuration idea from ViewResult; namely, that it looks for a corresponding action in the current controller if you don't specify which controller to look in.
o    RedirectToAction has many overloads that allow you to specify controllers, actions, route values, etc. It's probably the second most common ActionResult derived class, because it's so readable.

·         HttpStatusCodeResult
o    HttpStatusCodeResult return an HTTP status code to the browser, along with a custom message to be displayed:

        public HttpStatusCodeResult UnauthorizedStatusCode()
        {
            return new HttpStatusCodeResult(HttpStatusCode.Unauthorized, "You are not authorized to access this controller action.");
        }

        public HttpStatusCodeResult BadGateway()
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadGateway, "I have no idea what this error means.");
        }

·         HttpUnauthorizedResult
o    Returning an HttpUnauthorizedResult is the same as returning HttpStatusCodeResult with HttpStatusCode.Unauthorized, it's just more readable:








public HttpStatusCodeResult UnauthorizedResult()
{
return new HttpUnauthorizedResult("You are not authorized to access this controller action.");
}

·         HttpNotFoundResult
o    This is also an overload of HttpStatusCodeResult, but unlike HttpUnauthorizedResult, it actually does have a helper method

public HttpNotFoundResult NotFound()
{
return HttpNotFound("We didn't find that action, sorry!");
}


Comments

Popular posts from this blog

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome

Code First Getting Started

In this tutorial let us create a simple application to demonstrate the use of entity framework using code first. We are using Visual Studio 2015 and entity framework 6.1.3. You can download Visual Studio community Edition . You should have the basic knowledge of .Net framework, C# and MS SQL Server. In this tutorial, we will create a simple application with a user class.  Our user class will have basic information like name and email address of the user. Create the Project Open Visual Studio. File ->New -> Project Select C# -> Select Console Application Name the application as “EFGettingStarted” Click on OK Install Entity Framework The next step is to install the Entity framework. This can be installed via nuget package console. Click on Tools->Nuget Package manager -> Package Manager Console and type the following command C# 1 2 3   install - package entityframework   This will install the late

First, FirstOrDefault, Single, SingleOrDefault In C#

For people who are new to LINQ, it is difficult to understand the difference between First, FirstOrDefault, Single, SingleOrDefault. In this blog, I will explain what to use and when.     I will take a simple example to make you understand practically how these methods work.   Consider a class Employee with properties as Id, Name, and Department. class  Employee {    public   int  Id {  get ;  set ; }    public   string  Name {  get ;  set ; }    public   string  Department{  get ;  set ; } } I have a list of Employees: List<Employee> employeeList =  new  List<Employee>(){    new  Employee() { Id = 1, Name =  "Sunny" , Department =  "Technical"  },    new  Employee() { Id=2, Name= "Pinki" , Department = "HR" },    new  Employee() { Id=3, Name= "Tensy" , Department = "Finance" },    new  Employee() { Id=4, Name= "Bobby" , Department = "Technical" },    new