Wednesday, June 5, 2013

Action Result in MVC


In MVC Action result is a special class. This is described generally as the result of an action method, The Action method can be any method within our controller. Action Result is used to perform an operation on behalf of the action method. Thus we can say that the ActionResult are the Outcome of any action.

This class is derived from the System.Object class directly and it is present inside the System.Web.Mvc

The Assembly for this class is  System.Web.Mvc (in System.Web.Mvc.dll)
System.Object  >>   System.Web.Mvc.ActionResult

Now, this ActionResult work as a base class and we have multiple child classes which are derived from ActionResult base class.


Action Result is an Abstract class, thus we can have some concrete method and non-concrete method inside this class. The syntax fir this class is as
public abstract class ActionResult

Some of the Method expose by this class are.

1.       Equals
2.       ExecuteResult
3.       Finalize
4.       GetHashCode
5.       GetType
6.       MemberwiseClone
7.       ToString

There are several child classes that are derived from this class. Each class can be used for different purpose and are quite useful in performing our operation. Here we are going to see one by one which class is used for which purpose.

·         ContentResult :  This can be a Userdefined result of the action method.

public ActionResult TestAction(bool id, string strMsg) {
    if (id != 0)
        return Content(Server.HtmlEncode((strMsg.ToLower())));
    else
        return Content(Server.HtmlEncode(strMsg));
}


·         EmptyResult : Is used when the action method does not result anything, This type of result is nothing or empty.
public EmptyResult TestAction(bool id, string strMsg) {
        // ur logic
            return new EmptyResult();

}


·         FileResult :-  If we have to return a binary file as an output or result then the FIleResult class is used.

public FileContentResult DownloadFile(int fileId)
    {
        // load file content from db or file system
        string fileContents = "Test file content ";

        // convert to byte array
        // use a different encoding if needed
        var encoding = new System.Text.ASCIIEncoding();
        byte[] returnContent = encoding.GetBytes(fileContents);

        return File(returnContent, "application/CSV", "testingResult.csv");
    }


·         HttpUnautorizedresult: - If any request is unauthorized http request then we can use this action result to perform the output operation.


public ActionResult Index(string userName)
{
   If(username == null)
  return new HttpUnauthorizedResult();
}

·         JavascriptResult:- If we have to add a JavaScript result in the response then we make use of this action method.

public ActionResult TestJavaResult() {  
    string s = "$('#test-div').html(Tested!!!');";  
    return JavaScript(s);  
} 


·         JsonResult:   JSON formatted content in the response can be send by using this action result. Generally used for Ajax posting result.

public JsonResult GetJson()
{
                        return Json(resultset, JsonRequestBehavior.AllowGet);
 }


·         RedirectToActionResult : This action result redirect to a particular URL as a result of the action method.

public ActionResult Index()
{
    //All redirect here
    return RedirectToAction("Test", "Test");
}


·         RedirectToRouteResult:- If we are using any specified route for redirecting then this action result class is used.

     filterContext.Result = new RedirectToRouteResult(test);

·         ViewResultbase:- If we have to bind a Model with a view then we use this action result so that a view can be returned as an output with required model value.

    public ActionResult HelloWorld()
    {
        ViewData["Message"] = "Hello .Net Helper!!!";
        return View();
    }



Hope You  got the basic details about the ActionResult class and all its derived classed. These are very commonly used Actionresult in the programming. Please share your thoughts on the same.

Thanks
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM


Kontera