In this article I will try to explain different action results available in MVC and its uses with simple examples.
In MVC all actions are performed through controller. Controller assume each method as an action. Each action method has a return type and we call it as action result. There are plenty of action results are available according to need but all action results are inherited by ActionResult class. This is the base action result used in controller to perform any type of action. We can return any action type with ActionResult class. Let see action results with some example.
It is preferred to make a method private if it is not an action method.
There is a list of action results type available to be used as return type of a method in controller and ActionResult class is the base class for all. It means this type can be used with any method as a result. First of all let us see different types of action results available and then we can discuss each one by one. For more details please click on this link.
Action Result | Associated Method | Description |
---|---|---|
ViewResult | View() | Renders a view. |
PartialViewResult | PartialView() | Renders a partial view. |
RedirectResult | Redirect(), RedirectPermanent() | Redirects to another action method using URL in method. |
RedirectToRouteResult | RedirectToAction(), RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent() | Redirects to action. |
ContentResult | Content() | Returns content. |
FileResult | File() | Returns file or binary output. |
JsonResult | Json() | Returns Json. |
JavaScriptResult | JavaScript() | Returns JavaScript code to client. |
HttpNotFoundResult | HttpNotFound() | Returns an error page showing File not found error message - 404. |
EmptyResult | none | Returns null or void. |
FileResult is the base class of few more action results like FileContentResult, FilePathResult and FileStreamResult. All these uses File() method to render with different signatures.
Let's discuss each of them one by one. The most commonly used action results are ViewResult, PartialViewResult and JsonResult.
Used to renders a view. Below code will render Index view.
public ActionResult Index()
{
//It will render index view.
return View();
}
You can also render view by passing view name in View() method like below. Below method will render Login view.
public ViewResult CallViewResult()
{
return View("Login");
}
This is used to renders a partial view. Below method takes int parameter and passing it as model. Also note that I am using HttpPost method type so this method cannot be directly called from browser.
/// <summary>
/// This method returns a partial named _InnerPartial
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[HttpPost]
public PartialViewResult CallPartial(int value)
{
return PartialView("_InnerPartial", value);
}
By default no method type is defined on action method and it can be access as get or post. But if you define method type as HttpPost, it means it is of post type and if you define it as HttpGet then it is of get type.
Used to redirects to another action method using URL in method. Below method will be redirected to given url.
public RedirectResult CallRedirectResult()
{
//Redirect to given url
return Redirect("/Example/Index");
}
You can also permanently redirect to a perticular url with RedirectPermanent() method.
public RedirectResult CallRedirectPermanentResult()
{
//url to redirect
return RedirectPermanent("/Example/Index");
}
Used to redirects to another action. You can use RedirectToAction() method to perform this task or you can use RedirectToRoute() method. Let's first see RedirectToAction() method. We pass action name in this method and it will redirect to that method.
/// <summary>
/// This method will search for route url in route table (RouteConfig.cs) and if found, it will show that route url in url else it will show action name.
/// This example will show route name in url as I have defined route for the method CallViewResult()
/// </summary>
/// <returns></returns>
public RedirectToRouteResult CallRedirectToAction()
{
TempData["mess"] = "Redirected from CallRedirectToAction method...";
//I have defined a route 'MyTestRoute' for this action and when CallRedirectToAction() method will execute, it will replace url with that route url.
return RedirectToAction("CallViewResult");
}
Now let's see an example of RedirectToRoute() method. Here we pass route name what we have defined in route table.
public RedirectToRouteResult CallRedirectToRoute()
{
TempData["mess"] = "Redirected from RedirectToActionPermanent method...";
//put name of route and it will redirect to the url defined for that route.
//Below is the route defined in RouteConfig.cs
//routes.MapRoute(name: "RouteDefault",url: "MyTestRoute",
// defaults: new { controller = "Example", action = "CallViewResult"});
return RedirectToRoute("RouteDefault");
}
We can return content with this result type. In below example I have created a small HTML template and rendered it with the help of ContentResult.
public ContentResult CallContentResult()
{
System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
stringBuilder.Append("<div style='width:100%;background-color:#ccc; float:left;padding-left:10px;'>");
stringBuilder.Append("<h1>This is header</h1>");
stringBuilder.Append("<h2>This is second header</h2>");
stringBuilder.Append("<h3>This is third header</h3>");
stringBuilder.Append("</div>");
return Content(stringBuilder.ToString());
}
You can render a file or binary output with this result.
/// <summary>
/// This will render image file
/// </summary>
/// <returns></returns>
public FileResult CallFileResult()
{
string file=Server.MapPath("~/Files/fileupload.png");
return File(file, "image");
}
Returns JSON result to client.
public JsonResult CallJsonResult()
{
return Json(new { Message = "This is JSON data", JsonRequestBehavior.AllowGet });
}
Returns javascript result to ajax call.
public JavaScriptResult CallJavaScriptResult()
{
return JavaScript("alert('hello');");
}
Returns HTTP Not Found error page.
/// <summary>
/// Inherited from HttpStatusCodeResult class whose base class is again ActionResult class. Means HttpNotFoundResult>HttpStatusCodeResult>ActionResult
/// </summary>
/// <returns></returns>
public HttpNotFoundResult CallHttpNotFoundResult()
{
//Will render error page- Not found with message you are passing
return HttpNotFound("I am testing error");
}
Returns null result.
public EmptyResult CallEmptyResult()
{
//when nothing to return, can use this result.
return null;
}
Hope it can help. Please do your own research and enjoy.