[SOLVED] Calling a function from a C# API controller with Axios

Issue

I have function in a C# controller file that makes an API call to fetch some placeholder data that is hard coded locally.

[Route("api/ReportingCenter/GetReportList")]
[HttpGet]
public class ReportController : ApiController
{
   public async Task<IHttpActionResult> GetReportList(CancellationToken cancellationToken)
   {
       using (var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
                       HttpContext.Current.Response.ClientDisconnectedToken))
       {
           var userId = 11;
           var projId = 22;
           using (var reportDb = new ReportDb(userId, projId))
           {
               var list = reportDb.GetReports(userId, projId);
               return Json(list);
           }
       }
    }
}

public class ReportDb : PortalDb
{
    public List<ReportInfo> GetReports(int userid, int projectid)
    {
        var ReportList = new List<ReportInfo>();
        ReportList.Add(new ReportInfo(1,"file1.pdf", 11, "a file with data in it", 11112222,"pdf", 1, "22"));

    }
}

I coded a button and a function with an aspx file that should make an axios call to run the GetReportList function from the controller. When the button is click, nothing happens. Any suggestions on how to make it so that the API call is made when the button is clicked in the aspx file?

<asp:Content ID="Content5" ContentPlaceHolderID="primaryContent" runat="server">
    <div id="reporting-app-container">
        <input type="button" value="ReportInfo" class="btn btn-sm btn primary" 
        onclick="getReportInfo"/>
    </div>

    <script src="/ReportsModule/app/dist/reporting-app-bundle.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            window.ReportingApp();
        });

        async function getReportInfo(id) {
            console.log("pre-axios call")
            const response = await axios.get("api/ReportingCenter/GetReportList")
                .then(function (response) {
                    // handle success
                    console.log(response);
                })
                .catch(function (error) {
                    // handle error
                    console.log(error);
                });
        }
    </script>
</asp:Content>

Solution

Moved the javascript function that handles the axios call into reporting-app.js. Vue is being used on top of javascript. The .aspx file and the Vue app are connected by the "el" key, with the value set to the html id: ‘#reporting-app-container".

.aspx file

<div>HELLO WORLD!</div>
<div id="reporting-app-container">
    <input type="button" value="ReportInfo" class="btn btn-sm btn primary" @click="getReportInfo" />
</div>

<script src="/ReportsModule/app/dist/reporting-app-bundle.js"></script>

.js file

import Vue from 'vue';

window.ReportingApp = function () {
    new Vue({
        el: '#reporting-app-container',
        //store: FilesStore,
        data: {},
        components: {
            'reporting-component': reporting_component,
            'list-reports-component': list_report_component
        },
        methods: {
            getReportInfo: function (id) {
                console.log("pre-axios call");
                axios.get("/api/ReportingCenter/GetReportList")
                    .then(function (response) {
                        // handle success
                        console.log(response);
                    })
                    .catch(function (error) {
                        // handle error
                        console.log(error);
                    });
            }
        }
    });
}

The javascript and the C# Controller file are linked by the axios method within the methods section of the Vue app.

Controller.cs

using ###.###.###.api.Models;
namespace ###.###.ReportsModule.api
{
    public class ReportController : ApiController
    {
        protected readonly IPortalStateService PortalState;

        public ReportController(IPortalStateService portalStateService)
        {
        PortalState = portalStateService;
        }

        [Route("api/ReportingCenter/GetReportList")]
        [HttpGet]
        public IHttpActionResult GetReportList(CancellationToken cancellationToken)
        {
            using (var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
                       HttpContext.Current.Response.ClientDisconnectedToken))
            {
                var user = PortalState.GetUserId();
                if (user == null)
                {
                    return BadRequest("User is not allowed");
                }

                var userId = 11;
                var projId = 22;
                try
                {
                    using (var reportDb = new ReportDb(userId, projId))
                    {
                       var list = reportDb.GetReports(userId, projId);
                       return Json(list);
                    }
                }
                catch (Exception e)
                {
                    return Json(e);
                }
            }
        }
    }
        
    public class ReportDb : PortalDb
    {
        public List<ReportInfo> GetReports(int userid, int projectid)
        {
            var ReportList = new List<ReportInfo>();
            ReportList.Add(new ReportInfo(1, "file1.pdf", 11, "a file with data in it",
                                          11112222, "pdf", 1, "22"));
        return ReportList;
        }
    }
}

GetReports function uses the model from ReportInfo.cs that defines the field values and the constructor for the data.

ReportInfo.cs Model

namespace ###.###.reportsmodule.api.Models
{
    public class ReportInfo
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public int Ordinal { get; set; }
        public string Description { get; set; }
        public int ProjectId { get; set; }
        public string SourceType { get; set; }
        public int MinPermissionLevel { get; set; }
        public string SourceId { get; set; }

        public ReportInfo(long id, string name, int ordinal, string description,
                          int projectId, string sourceType, int minPermissionLevel, string sourceId)
        {
            Id = id;
            Name = name;
            Ordinal = ordinal;
            Description = description;
            ProjectId = projectId;
            SourceType = sourceType;
            MinPermissionLevel = minPermissionLevel;
            SourceId = sourceId;
        }
    }
}

Answered By – minTwin

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *