Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Action Result And Return Type

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.06k
    Comment on it

    Action Result And Return Type In ASP.NET MVC

    An ActionResult is return type of method/action defined in a controller. ActionResult is a class defined in namespace System.Web.Mvc. Result returned by action/method is called action result. We can return any type of object such as string,integer or boolean and these are wrapped into appropriate ActionResult before they are rendered. ActionResult is base class of all action result.

    List of ActionResult

    1)ViewResult

    2)PartialViewResult

    3)RedirectToRouteResult

    4)JsonResult

    5)JavaScriptResult

    6)ContentResult

    7)HttpStatusCodeResult

    8)HttpUnauthorizedResult

    9)HttpNotFoundResult

    10)FileResult

    11)FileContentResult

    12)FilePathResult

    13)FileStreamResult

    14)RedirectResult

    15)EmptyResult

    When to use ActionResult ?

    As ActionResult is base class for all the actions performed so you can use ActionResult as a return type for any type of action result. But when you have have to return different action result based on conditions then you must use ActionResult as return type.

    Example

    public ActionResult MultipleActionResult()
    {
        if(condition)
        {
            return RedirectToAction("ActionName","ControllerName","Route Values");
        }
        else
        {
            return View();
        }
    } 
    

    Here you can't use "RedirectToRouteResult" or "ViewResult" as a return type as in case of ViewResult as return type if condition is true then you have to redirect to another action which can't be handled by ViewResult and in case of RedirectToRouteResult as return type if condition is false then you have to return view which can't be wrapped into RedirectToRouteResult. So, it is better to use ActionResult as return type as it is base class for all actions and can wrap any type of action.

    I am going to explain first six action result for more you may refer to MSDN.

    1)ViewResult

    Returns a view to render as a web page.

        public ViewResult Index()
        {
            ICollection<Projects> projects = builderProjectControllerApi.GetProjects();
    
            if (projects == null)
            {
                ModelState.AddModelError("error", "Problem in getting records.");
                return View();
            }
            else
            {
                return View(projects);
            }
        }
    

    Here, View is strongly bind to a model "project" and I am returning a collection of project to view. We can use ActionResult as return type instead of ViewResult as ActionResult is base class of all actions.

    2)PartialViewResult

    Returns a partial view that has to be render within another view.

        public PartialViewResult NewSpecificationRow(int id, string contactName, string landlineNumber, string  mobileNumber)
        {
            var info = new ContactDetail { ContactId=id,ContactName=contactName,LandlineNumber=landlineNumber,MobileNumber=mobileNumber};
            return PartialView("&#95;NewContactDetails", info);
        }
    

    ContactDetail is a class which is model for partial view "_NewContactDetails". Details are wrapped into info and passed to partial view. From main view there is ajax call to this method to render partial view. We can use ActionResult as return type instead of PartialViewResult as ActionResult is base class of all actions.

    3)RedirectToRouteResult

    Redirects to another action of same controller or action of some other controller.

    [HttpPost]
    public RedirectToRouteResult NewSpecificationRow(Student student)
    {
        string name1 = student.Name;
        int id = student.Id;
        string address = student.Address;
            return RedirectToAction("Save", new { name = name1});
    }
    
    public ActionResult Save(string name)
    {
       ViewBag.Name = name;
       return View("Save");
    }
    

    Here, we are setting name1 with a value of student's name and redirecting to another action save and passing name1 as a parameter value. We can use ActionResult as return type instead of RedirectToRouteResult as ActionResult is base class of all actions.

    Redirecting to action in another controller-:

       [HttpPost]
            public RedirectToRouteResult NewSpecificationRow(Student student)
            {
                string name1 = student.Name;
                int id = student.Id;
                string address = student.Address;
                return RedirectToAction("ActionName","ControllerName", new { name = name1});
            }
    

    4)JsonResult

    Returns object in JSON format.

        [HttpPost]
        public JsonResult Save(Student student)
        {
    
            string name = student.Name;
            int id = student.Id;
            string address = student.Address;
    
            return Json("object received");
        }
    

    Here, I have sent object of student from view through ajax call and sending message "object received" to view on receiving the object. We can use ActionResult as return type instead of JsonResult as ActionResult is base class of all actions.

       [HttpGet]
        public JsonResult Display()
        {
            Student s = new Student();
            s.Name = "priyank";
            s.Id = 3;
            s.Address = "Clementown";
            return Json(s, JsonRequestBehavior.AllowGet);
        }
    

    Here, we are sending object from controller to view in a JSON format. JsonRequestBehavior.AllowGet is used to enable "Get". We can use ActionResult as return type instead of JsonResult as ActionResult is base class of all actions.

    5)JavaScriptResult

    Returns script that has be executed on client side.

    Index.cshtml
    <input type="button" id="checkjs" name="submit" value="Javascript" onclick="renderJs()">
    <div id="mydiv"></div>
    

    Here, we have button on clicking which we will have an ajax call to function renderJs() defined in JS which in turn calls renderJs() defined in controller which will insert text within div.

     script
     function somefunction()
     {
    
     }
    
     function renderJs()
        {
            $.ajax({
    
                type: "POST",
                url: "Home/renderJs",
                contentType: "application/json; charset=utf-8",
                dataType: "script",
    
        });
    
    controller
            [HttpPost]
            public JavaScriptResult renderJs()
            {
               string js="document.getElementById('mydiv').innerHTML='Example to show JavaScriptResult '";
               return JavaScript(js);
            }    
    

    Output- In controller,we have string to insert text within div.It will show the specifed text on your browser.

    If you have to call some other function defined in script say "somefunction()" then you have to do something like this -:

    [HttpPost]
        public JavaScriptResult renderJs()
        {
           string js="somefunction();";
           return JavaScript(js);
        }    

    6)ContentResult

    Use to return user defined content like sending message if ajax call is successful.

    On clicking button we have ajax call to method/action of controller which in turn returns the message "Ajax Call is Successful" if ajax call is successful. Parameter response of success function of ajax call contains the message returned by the user.

    <input type="button" id="check1js" name="submit" value="content" onclick="content()">
    
     function content() {
            $.ajax({
    
                type: "POST",
                url: "Home/content",
                contentType: "application/json; charset=utf-8",
                dataType: $(this).serialize(),
                success: function (response) {
                    alert(response);
    
                }
    
            });
    
        }
    
    [HttpPost]
     public ContentResult content()
    {
        string response = "Ajax Call is Successful";
        return Content(response);
    }
    

    7)HttpStatusCodeResult

    Returns a specific HTTP response code and description.

    8)HttpUnauthorizedResult

    Returns the result of an unauthorized HTTP request.

    9)HttpNotFound

    Indicates the requested resource was not found.

    10)FileResult

    Returns binary output to write to the response.

    11)FileContentResult

    Use when you have to write content of binary file to response.

    12)FilePathResult

    Use when you have to write content of file to response.

    13)FileStreamResult

    Writes content of file on response through a stream.

    14)RedirectResult

    Redirects to another action using its URL.

    15)EmptyResult

    To return nothing or null.

    References

    http://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult(v=vs.118).aspx

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: