Various return type of action in MVC application
Various return types of action in MVC application
In this article we will discuss various return types of
Action. Generally in MVC application the default return type of action is
ActionResult but we can return those type of value whose class is derive from
ActionResult class. Here we will see
various return types one by one with example.
Return default View
If we do not specify any view name when we want to return
view then by default, default view will be returned. In below example, from Index action we are
returning view but we did not specify view name, then by default it will call
the view which is attached with this action.
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
}
Return Specific view from Action.
If we don’t want to call default view then we can specify
view name. For example in below example we have specify view name. We have to
keep in mind that the view should be in the same controller folder. Otherwise
we have to keep view in shared folder.
public class TestController : Controller
{
public ActionResult Index()
{
return View("Index");
}
}

Return
content
Sometimes it
needs to return raw string data rather than calling any view. In this situation
we can return content. In below example we are returning Content and it will
return simple string in browser.
public class TestController : Controller
{
public ActionResult Index()
{
return Content("The content is return from Action");
}
}

Return to
Different Action
This is
common situation where it needs to call other action from some other action. In
below example we have created two actions in Test controller. Where from Index
action we will call Called action. To do same ,we have to use
RedirectToAction() function.
public class TestController : Controller
{
public ActionResult Index()
{
return RedirectToAction("Called");
}
public ActionResult Called()
{
return Content("Called by Index Action");
}
}

Now,
please note that both actions are in same controller. When both actions are in
same controller then action name is enough to call specific action.
Redirect to Different Action within same or different
controller
When we want to call any action which belongs to different controller,
we have to specify path of that controller. In below example we want to call
Called action which belongs to Test1 controller from Index action which belongs
to Test controller.
public class TestController : Controller
{
public ActionResult Index()
{
return RedirectToAction("../Test1/Called");
}
}
public class Test1Controller : Controller
{
public ActionResult Called()
{
return Content("Called from Test Controller");
}
}

Conclusion:-
In this article we have seen how to call view and action from any other action. There are many more return type of action. In next few articles we will discuss them.