PBMining

Searching...
Thursday, June 21, 2012

Play with action result in asp.net MVC

9:53 AM

MVC provides many different type of ActionResult for create a response of action all those result are derived from ActionResult class.some common action result is that we generally used is ViewResult for rendering html to the response.In this post i am going to explain about some very useful action result classes. for render all action result you can use a single base class ActionResult. but we suggest you to use most specific class when you know the type of result return by the action.

ViewResult

        Function RenderView() As ViewResult
            Return View()
        End Function
    

above is simple definition that return the view RenderView.

PartialViewResult

        Function RenderView() As PartialViewResult
            Return PartialView()
        End Function
    

Above two common ActionResult is use to render View to response.MVC provide helper method that create new instance of appropriate ActionResult .In above examples we used View(),PartialView() helper method. it has many overload for passing ViewName and data to the view.

above action result is for render the view.MVC provides action result for redirect to another action method or path or specific route.

RedirectResult

     Function RedirectResult1() As RedirectResult
            Return New RedirectResult("~/Derived/Index")
        End Function
    

RedirectToRouteResult

     Function RedirectToRoute1() As RedirectToRouteResult
            Return RedirectToRoute(New With {.controller = "Test", .action = "Index", .query = "all", .page = 555})
        End Function

        Function RedirectToAction1() As RedirectToRouteResult

            Return RedirectToAction("Index", "Derived", New With {.query = "All", .page = 555})
        End Function
    

In above examples we used two action result RedirectResult and RedirectToRouteResult both of these are used for redirection.RedirectResult helper method take URL to redirect as parameter. and RedirectToRoute and RedirectToAction both return RedirectToRouteResult. RedirectToRoute helper method take object contain a segment values that is passed to route.RedirectToAction helper method takes a parameter for actionName and controllerName and additional values that is going to pass to the action method.

Other types of action results for returning different type of content like XML ,Json,Text,File .all those result are derived from ContentResult Base class.and classes derived from ContentResult are JsonResult,FileResult. these both classes created for special purpose.other content types can be handle by contentType parameter of helper method.

ContentResult

        Function PlainText() As ContentResult
            Return Content("hello,how r u?", "text/plain", Encoding.Default)
        End Function

        Function XMLContent() As ContentResult
            Dim persons = GetPersons()
            Dim xmldata As XElement = New XElement("PersonList", persons.Select(Function(p)
                                                                                   Return New XElement("Person", New XAttribute("FirstName", p.FirstName),
                                                                                                                   New XAttribute("LastName", p.LastName),
                                                                                                                    New XAttribute("Gender", p.Gender))
                                                                                End Function))

            Return Content(xmldata.ToString, "text/xml")

        End Function
        
    

as you can see in above method we used Content helper method that is provided by MVC.and pass content as first parameter and in second parameter we define type of content is going to return.it will overwrite Response.ContentType property of response object. and in third parameter we define Encoding for content that is default.

next class for returning Json result there is one inbuilt class for provided by MVC JsonResult and Json() helper method for generate json result from collection.

JsonResult

 Function JsonContent() As JsonResult
            Dim persons = GetPersons()

            Return Json(persons)

        End Function

its just a simple implementation we create persons details from GetPersons method and pass that collection object to Json helper method it create Json formatted string from collection,set response content type to text/json and return json string output.

FileResult

our next implementation is to use FileResult class which is use to send file to browser. File helper method is available.it has many overload for sending file from disk,stream and from in memory data.


  Function FileDownload() As FileResult
            Dim filepath = "d:\report.pdf"
            Dim contenttype = "application/pdf"
            Dim downloadname = "Report.pdf"

            'send file by path
            Return File(filepath, contenttype, downloadname)

        End Function

        Function ByteDownload() As FileResult
            Dim filepath = "d:\report.pdf"
            Dim contenttype = "application/pdf"
            Dim downloadname = "Report.pdf"

            'given alias name of file class as it conflict with helper method name
            Dim filedata = IOfile.ReadAllBytes(filepath)

            'send file as bytes
            Return File(filedata, contenttype, downloadname)

        End Function


        Function StreamDownload() As FileResult
            Dim filepath = "d:\report.pdf"
            Dim contenttype = "application/pdf"
            Dim downloadname = "Report.pdf"

            Dim filestream = IOfile.OpenRead(filepath)

            'send file from stream
            Return File(filestream, contenttype, downloadname)

        End Function

In above example we created three action method for show different overloads of File helper method.In first action method we just pass file path, content type and download name that is shown in browser dialog. In second action method we read file bytes from disk and pass the bytes data to helper method.same in third action method we open file stream from filepath and pass stream to File helper method.

HttpStatusCodeResult

Our last implementation is use of HttpStatusCodeResult.which is use to send a specific http status code response to browser.In MVC there are helper method specific to some http status code like for 404 code HttpNotFound helper method is available for other you have to manually create an instance of HttpStatusCode result instance with parameter.

 Function Http404Status() As HttpStatusCodeResult
            Return New HttpStatusCodeResult(404, "Requested resource not found.")
            'Return HttpNotFound("Requested resource not found.") 'both produce the same result


        End Function

        Function Http401Status() As HttpStatusCodeResult
            Return New HttpStatusCodeResult(401, "Unauthorized access")
            'Return New HttpUnauthorizedResult("Unauthorized access")  'both produce the same result


        End Function

you can use helper method or you can create instance of specific action result class to generate response.

1 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Write your review about this post.