'How to return the View with JSON result?

Is there any way to return the View with JSON result? I've done like this but it returns me a json results only I want to bind json result with jQuery Datatable.

this is my controller:

[HttpGet]
    public async Task <IActionResult> GetDepartments()
    {
        try
        {
            ...
            var result = await _get.GetRequest<string>(uri, accessToken);
            return Json(result);
            }
        }

        catch (Exception ex)
        {
           ..
        }

For my View I'm doing like this:

<table id="myDataTable">
    <thead>
        <tr>
            <td>Id</td>
            <td>Name</td>
            <td>Department</td>
            <td>Manager</td>

        </tr>
    </thead>
    <tbody>
    </tbody>

</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js"></script>
<script>
        $(document).ready(function () {
            $('#myDataTable').DataTable({
                ajax: {
                    url: '/Home/GetDepartments',
                    "dataSrc": ""
                },
                columns: [
                    { data: "id" },
                    { data: "name" },
                    { data: "department" },
                    { data: "manager" }
                ]
            });
        });


</script>

That's what I got

[{"id":3,"name":"Sales","department":null,"manager":"Danial Booker"},{"id":4,"name":"PMO","department":null,"manager":"Rowan Walter"},{"id":5,"name":"Research And Development","department":null,"manager":"Shani Elliott"},{"id":6,"name":"Product Management","department":null,"manager":"Menna Goff"},{"id":7,"name":"HR","department":null,"manager":"Jayda Martinez"},{"id":8,"name":"Deve","department":"Product Management","manager":"Abigayle Briggs"},{"id":9,"name":"Test","department":"Product Management","manager":"Alys Huang"},{"id":19,"name":"QA","department":"Ava","manager":"Mela "}]

I want to show the view that have the Plugin jQuery datatable with json result, any help please?



Solution 1:[1]

first, you have to make an ajax call to fetch the data then you can bind it. if you have data you can bind it in your data table something like the below example.

 var data = [{"id":3,"name":"Sales","department":null,"manager":"Danial Booker"},{"id":4,"name":"PMO","department":null,"manager":"Rowan Walter"},{"id":5,"name":"Research And Development","department":null,"manager":"Shani Elliott"},{"id":6,"name":"Product Management","department":null,"manager":"Menna Goff"},{"id":7,"name":"HR","department":null,"manager":"Jayda Martinez"},{"id":8,"name":"Deve","department":"Product Management","manager":"Abigayle Briggs"},{"id":9,"name":"Test","department":"Product Management","manager":"Alys Huang"},{"id":19,"name":"QA","department":"Ava","manager":"Mela "}];
 
 $('#example').DataTable({
       data : data,
       columns : [
           { "data" : "id" },
           { "data": "name" },
          { "data": "department" },
          { "data": "manager" }
      ]
}) 

here is a working example.

Solution 2:[2]

The way you are trying now you should have two controller one for fetching data and another one for displaying the datatable into view

Controller For Feching Data:

        [HttpGet]
        public async Task<IActionResult> GetDepartments()
        {
            try
            {

                var result = await _get.GetRequest<string>(uri, accessToken);
                return Json(result);

            }

            catch (Exception ex)
            {

            }
        }

Note: You don't need to add view for this action

Controller For Display Datatable:

        [HttpGet]
        public IActionResult BindJsonToView()
        {
            return View();
        }

Note: Add below view for this action as below

View To Display Datatable:

<h2>BindDataTableFromJson</h2>
<table id="bindDataTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Department</th>
            <th>Manager</th>

        </tr>
    </thead>
</table>
@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {


            $.ajax({
                type: "GET",
                url: "/ControllerName/GetDepartments",
                success: function (response) {
                    $('#bindDataTable').DataTable({
                        data: response,
                        columns: [
                            { data: 'id' },
                            { data: 'name' },
                            { data: 'department' },
                            { data: 'manager' }
                        ]
                    });

                },
                error: function (response) {
                    alert(response.responseText);
                }
            });

        });
    </script>
}

Output:

enter image description here

Another easy way, you could try, you don't need to use two controller, only need to use ViewBag instead of Json(result) Just plug and play.

Controller:

        [HttpGet]
        public IActionResult BindDataTable()
        {
            var result = await _get.GetRequest<string>(uri, accessToken);
            ViewBag.result = result;
            return View();
        }

View:

@{
    ViewData["Title"] = "BindDataTable";
}
    <table id="bindDataTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Department</th>
                <th>Manager</th>
    
            </tr>
        </thead>
    </table>
        @section scripts {
            <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
            <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    
            <script>
    
            $(document).ready(function () {
            $('#bindDataTable').DataTable({
                data:  @Json.Serialize(@ViewBag.result),
                columns: [
                    { data: 'id' },
                    { data: 'name' },
                    { data: 'department' },
                    { data: 'manager' }
                  
                ]
            });
            });
            </script>
        }

Output:

enter image description here

You have both the options , now choice is yours. Hope it would help you to figure out

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Negi Rox
Solution 2