Using Javascript to invoke an API in ASP.NET core

I have used the dotnet command line to create a new ASP.NET core web site to host the customer portal which will allow for people to access the functionality of Get Homii via a web site.

dotnet new mvc -o GetHomii.CustomerPortal

This will generate a basic .net core web site with bootstrap and jquery and to get started I have created a form that renders as follows:

I am using the bootstrap library and it’s grid framework to render the form and I will be writing some javascript to process the click of the ‘Check your borrowing power’ button.

The first step is to open the page /Views/Home/Index.cshtml and just above the closing /div put the following code:

<script language="javascript">
/**
    Invokes the loanamount API to get a calculation response
    Returns a Promise
*/
const getCalculationResponse = (rent) => {
    const url = `https://gethomii-gateway.azurewebsites.net/api/v5/calculators/loanamount?rent=${rent}&isInvestor=N`;
    return window.fetch(url);
}
</script>

What the code is doing is creating a function called getCalculationResponse that will wrap the window.fetch that I setup in my previous post http://munceyweb.com/2019/06/06/using-the-javascript-console-to-test-a-api/. This function will return a promise which can be handled by the calling function. You can test the function operation at any stage by opening the developers console and typing the function name with a valid parameter. This is a good technique to remember as using the developers console in this way is a powerful way to debug any application that you are working on and to see what responses are coming back to API calls.

The other tab to be aware of is the Network tab as this will show you exactly what is being sent to and what is being retrieved from the API. This becomes very useful later on particularly when you are developing a new application and want to try out different scenarios without running the whole application. In the screen shot below I have invoked the API using the getCalculationResponse function and I am previewing the response to confirm operations.

The next step is to add a button handler for the check your borrowing power button. I have done this by adding the following code.

/**
    Button handler for the Check your borrowing power button 
*/
const onCalculate = () => {
    const rent = $('#rent').val();
    getCalculationResponse(rent)
        .then(response => response.json())
        .then(json => {
            console.log(json);
        })
}

This code will receive the response convert the response to json and will then write the response to the console.

Again this is a powerful programming technique and the approach I am taking is to build in a way where I test each step as I go rather than attempting to build the whole app first and then test it. I have found that this is the best way to build an app as it gives me an opportunity to test as much of the app as possible whilst building the application.

Now the next step is to add response handling code

        .then(json => {
            $('#results-PropertyValue').val(json.propertyValue);
            $('#results-InterestRate').val(json.interestRate);
            $('#results-Rent').val(json.rent);

            $('#calculateForm').addClass('d-none');
            $('#resultsForm').removeClass('d-none');
        })

Doing this will render the above form which will show the results of the calculation. There are a couple of additional steps that I want to take. The first is to implement the Check Again button and the second is create a Spinner to display when the calculation is taking place.

So lets go right ahead and do that. The Check Again button is easy to implement as it is simply a matter of hiding the results and showing the form again.

/**
    Button handler for the Check Again button
*/
const onGoBack = () => {
    $('#calculateForm').removeClass('d-none');
    $('#resultsForm').addClass('d-none');
}

For the Spinner I am using the boostrap spinner control https://getbootstrap.com/docs/4.3/components/spinners/

<div id="processing" class="d-none"> 
    <div class="spinner-grow" role="status">
        <span class="sr-only">Loading...</span>
    </div>
</div>

I have created a new element called processing when I want to show the element I use the removeClass jQuery function to remove the d-none class and to hide the element I add the d-none class back again. The onCalculate function now looks like the following:

/**
    Button handler for the Check your borrowing power button 
*/
const onCalculate = () => {
    const rent = $('#rent').val();
    $('#calculateForm').addClass('d-none');
    $('#processing').removeClass('d-none');
    getCalculationResponse(rent)
        .then(response => response.json())
        .then(json => {
            $('#results-PropertyValue').val(json.propertyValue);
            $('#results-InterestRate').val(json.interestRate);
            $('#results-Rent').val(json.rent);

            $('#calculateForm').addClass('d-none');
            $('#resultsForm').removeClass('d-none');
            $('#processing').addClass('d-none');
        })
}