Built-in ActionResult types

An action method respond to user input and return an action result. There are many derived ActionResult types in MVC that you may use to return the results of an action method. These are more specific for a particular view.

1. RedirectResult :-

Here, url you want to redirect is expressed as a string and passed as a parameter to the Redirect method. Redirect method send a temporary redirection.

public RedirectResult Index()
{
     return Redirect("/Demo/Index");
}

We can send permanent redirection using RedirectPermanent.

public RedirectResult Index()
{
     return RedirectPermanent("/Demo/Index");
}

2. RedirectToRouteResult :-

We can use routing system to generate valid url with RedirectToRoute method.

public RedirectToRouteResult Index()
{
     return RedirectToRoute(
     {
        controller="Demo"
        action="Index"
        ID=5
     });
}

For permanent redirection there is RedirectToRoutePermanent method.

RedirectToAction 

We can redirect to an action method by using RedirectToAction method.

public RedirectToRouteResult Index()
{
     return RedirectToAction("Index","Demo");
}

For permanent redirection there is RedirectToActionMethodPermanent method.

3. ContentResult :-

ContentResult is used for general purpose such as Xml, RSS, ATOM, Text(Plain), CSV.

public ContentResult Index()
{
     string message="Hi There!";
     return Content(message);
}

4. JSONResult :-

JSONResult is used for JSON.

public JsonResult JsonData()
{
     Storylink stories=GetAllStories();
     return Json(stories);
}

5. FileResult :-

FileResult is concerned with sending binary data to the browser.

public FileResult Report()
{
     string fileName=@"c:\Report.pdf";
     string contentType="application/pdf";
     return File(fileName,contentType);
}

This action method cause browser to prompt user to save the file.

6. HttpStatusCodeResult :-

We can send specific status code to the browser using HttpStatusCodeResult.

public HttpStatusCodeResult StatusCode()
{
     return new HttpStatusCodeResult(404,"url can't be serviced");
}

Note: There is no Helper method for this, so we must instantiate class directly

We can also achieve above code by using HttpNotFound method.

public HttpStatusCodeResult StatusCode()
{
     return HttpNotFound();
}

HttpUnauthorizedResult indicates that request is unauthorized.

public HttpStatusCodeResult StatusCode()
{
     return new HttpUnauthorizedResult();
}

Ebook Download
View all
Learn
View all