This is one hot question in .NET job interviews, I have heard from many of my friends. Developers with limited hands-on experience with MVC should be able to provide an answer to the question, because the scenario is very common and every now and then it needs to return something from the controller to the presentation environment.
We are very familiar with the “ActionResult” class that is the base class of many classes and we can return an object of those classes. The class hierarchy is as in the following:
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 very similar to the master page concept in Web Form applications. The partial view is nothing but pagelet, that we can return from the controller and that merges with the main view and generates one concrete HTML page.
It may take 4 parameters to render in the partial view.
Redirect
This is equivalent to Response.redirect() or Server.Transfer() functions. It takes the URL path to be redirect , though we can use Response.Redirect() or Server.Transfer() in MVC too.
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 JSON
This is very useful when we don't want an entire HTML page but only want a value. Generally in AJAX-based single-page applications we do not load an entire page again and again but load fresh data from the DB using AJAX. In this scenario we can return only a JSON object and in the success function of jQuery ajax (let's assume we are using the jQuery library to implement AJAX) we can just manipulate data.
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.
No comments:
Post a Comment