February 23, 2024 07:11 by
Peter
This is a popular question in.NET job interviews, as I've heard from several acquaintances. Developers with limited hands-on expertise with MVC should be able to respond to the question because the scenario is typical and requires returning anything from the controller to the presentation environment on a regular basis. We are extremely familiar with the "ActionResult" class, which is the base class for many classes and can return an object from those classes. The class structure is as follows:
System.Object
System.Web.Mvc.ActionResult
System.Web.Mvc.ContentResult
System.Web.Mvc.EmptyResult
System.Web.Mvc.FileResult
System.Web.Mvc.HttpStatusCodeResult
System.Web.Mvc.JavaScriptResult
System.Web.Mvc.JsonResult
System.Web.Mvc.RedirectResult
System.Web.Mvc.RedirectToRouteResult
System.Web.Mvc.ViewResultBase
In this example, we will see all of the derived classes that is inherited from the “ActionResult” base class. So, let's start one by one.
Return View
This is a most common and very frequently used type. We see that we can pass eight parameters when we return the view. We can specify the view name explicitly or may not.
Return partial View
The concept of a partial view is quite similar to the master page concept used in Web Form applications. The partial view is simply a pagelet that may be returned from the controller and combines with the main view to create a single tangible HTML page.
It may require four parameters to render in the partial view.
Redirect
This is comparable to the Response.redirect() and Server.Transfer() routines. It uses the URL path to redirect, however with MVC, we can instead use Response.Redirect() or Server.Transfer() instead.
Redirect To Action
Sometimes it is necessary to call another action after completion of one action, this is very similar to a function call in traditional function oriented programming or Object Oriented Programming. It may take 6 parameters. The first parameter is very simple, only action name.
Return content
This is useful when we want to return a small amount of strings from a controller/action. It takes three parameters. The first one is a simple string and the remaining two are strings with little information.
Return JavaScript
When we wanted to return a JavaScript string, we may use this function. It takes only one parameter, the string only.
Return File
We are allowed to return a binary file if needed from a controller. It takes 6 parameters maximum.
Conclusion
Those are all of the return types in an action in an MVC controller, but we rarely use them; in my limited experience, users prefer to return View() from the action. What say you? Have fun learning.