Example of a javascript fetch to a razor page

In this example, we have a database of tours with id, name, price, and other information. We would like to pull just the name and the price of the tour using a javascript fetch to a site hosting the razor pages.

We will use the index page on the server site and assume it has implemented entity framework with a class Tour. We create a new class, TourDetail, just to hold the Id, Name, and Price. We return the tour information as a JsonResult.

 

public Tour MyTour { get; set; }
public class TourDetail
   {
     public int Id { get; set; }
     public String Name { get; set; }
     public Decimal Price { get; set; }            
    }
public  IActionResult OnPostTourDetail(int tourID)
    {
      MyTour =  _context.Tours.FirstOrDefault(m => m.ID == tourID);
      return new JsonResult(new TourDetail{ Name = MyTour.Name, Price=MyTour.Price, Id=MyTour.ID});
     }

Preview in new tab

For the client side, we have a simple html file with a javascript function to fetch the result. The main javascript function fetches the data from example.com using a Post. Since the result is returned as json, it is easy to separate the parts of the data.

        
           function getInfo() {
            let formData = new FormData();
            var id = document.getElementById('tourID').value;
            formData.append('tourID',id );
            fetch('https://example.com/?handler=TourDetail', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then((data) => {
                    document.getElementById("name").innerText = data.name;
                    document.getElementById("price").innerText = formatMoney(data.price);
                });
        }

        function formatMoney(number) {
            return number.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
        }

The body of the page gives us an input box to enter the id of the tour, a button to click, and a means to display the results.

<h4>Tour data</h4>
    <div>Enter Tour ID:  <input type="text" id="tourID"></div>  
    <div> <button onclick="getInfo()"> Get Info</button></div>
    <blockquote>     
        <div id="name"></div>
        <div id="price"></div>
    </blockquote>

Leave a Reply

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