skip to Main Content

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>

2

Answers


  1. Chosen as BEST ANSWER

    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;
            }
        }
    }
    

  2. .then and .catch are methods of a Promise, which is what you’d get if you called axios.get without awaiting it. A Promise represents an action which you’ve started in the background, which may or may not have finished yet, and which can call callback functions supplied by you if/when it completes successfully or throws an error. Or at least that’s a very short description of what it is.

    To pass your callback functions to the Promise returned by axios.get, remove the async and await, a bit like this:

    function getReportInfo(id) {
      axios.get('api/ReportingCenter/GetReportList')
        .then(function (response) {
          // handle success
          console.log(response);
        })
        .catch(function (error) {
          // handle error
          console.log(error);
        })
        .then(function () {
          // always executed
        });
    }
    

    If you want response to be the actual response from the API, rather than a Promise to give you the actual response once the web request has completed, then you can await the Promise, a bit like this:

    async function getReportInfo(id) {
      try {
        const response = await axios.get('api/ReportingCenter/GetReportList');
        console.log(response);
      } catch (error) {
        console.error(error);
      }
    }
    

    A note of caution if you choose the second option – are you sure all your users’ browsers support ECMAScript 2017? If not then the await / async approach probably isn’t a good idea and you should stick with the first option.

    Code snippets are adapted from this bit of the axios API documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search