Custom Action Result Sample in MVC

Custom Action Result Sample in MVC

So far we have seen the following built-in action result types and the action helper methods that return them.

Action ResultHelper MethodLink
ContentResultContentContent Result: Day 9
RedirectResultRedirectRedirect Result: Day 10
ViewResultViewView Result: Day 11
JavaScriptResultJavaScriptJavaScript Result: Day 12
JsonResultJsonJSON Result: Day 13
HttpStatusCodeResult HttpUnauthorizedResult HttpNotFoundResultHttpNotFoundHttpNotFound Result: Day 14
FileResult FilePathResultFile File Result: Day 15

Now let's see the custom action result method step-by-step:

Create a MVC project from the "Empty" template.

Right-click on the project and select "Add" > "Class".

2.jpg

Name it "XMLResult".

3.jpg

Inherit the XMLResult class from ActionResult and override the "ExecuteResult" method.

Create an object of "HttpResponseBase" class, that is a base class for classes that provides Http response information from an ASP.NET operations.

Set the content type to application/XML. Create a parameterized constructor of the XMLResult class and pass a datatable as the parameter. Assign a datatable objet to the local datatable object inside the constructor. Create a dataset object inside the ExecuteResult method and add a datatable to that object.

4.jpg

Now add a controller. Right-click on "Controllers" then select "Add" >> "Controller".

5.jpg

Select "MVC 5 Controller – Empty" and press the "Add" button.

6.jpg

Name it as follows:

7.jpg

Create a datatable object and fill it with some values in the Index action result method.

Return XMLResult with datatable.

8.jpg

Now run the project and you will see that our datatable is converted into XML using our custom action result.

9.jpg