Controllers executes all incoming requests using Action method. An ActionMethod may return different type of result. In this blog, we will see about ActionResult of an ActionMethod in details.
What is ActionResult?
ActionResult
is the base class for all action results in MVC.
Whenever you create a controller class, a default action is created like this –
In below code, Action type is ViewResult
and View is a helper method:
public ActionResult Index()
{
return View();
}
The above code can be written in an alternate way.
public ViewResult Index()
{
//return View();
return new ViewResult();
}
Different types of ActionResult in MVC
ActionResult Type | Helper Method |
ViewResult | View() |
PartialViewResult | PartialView() |
RedirectResult | Redirect() |
ContentResult | Content() |
RedirectToRouteResult | RedirectToAction() |
FileResult | File() |
JsonResult | Json() |
Below is the sample code to show different helper method –
public ActionResult Index()
{
return new EmptyResult();
}
public ActionResult Index()
{
return Content("This is a Content");
}
Cannot implicitly convert type
System.Web.Mvc.ContentResult
to System.Web.Mvc.EmptyResult
public EmptyResult Index()
{
return Content("This is a Content");
}
If you will use ActionResult as return type then it will not throw any error as it is the base class for all type of action result.
So either use respective Result Type or use ActionResult for all returning helper method.
Hope it is clear to you, in case of any confusion open Visual Studio and try above-given code, you will get a clear picture about ActionResult.
Happy Learning 🙂