Async await method in razor page example

In this razor page tutorial you will learn, how to call async methods or async property in razor page onget method.

When you create a razor page by default one get method is created, like example below.

public class IndexModel : PageModel
    {     
        public void OnGet()
        {
        }
    }

In order to consume an async method or property inside the get method, you need to make the get method as async.

So you probably think of writing code like below, where you only add async keyword in default void get.

[BindProperties]
public class stockupdateModel : PageModel
{
	
	public async void OnGet()
	{
		BookingService bookingService = new BookingService();
		List<Stock> _stocks = await bookingService.GetStockDetails();
		StockList = _stocks;   
		
	}
}

The above code will not produce any error, but also will not work!

Because the type void is always based on "fire and forget" principal. As a result the property you are trying to bind with data, will NOT get loaded.

One solution, you can make the method async just by adding Async keyword, like "OnGetAsync"

[BindProperties]
public class stockupdateModel : PageModel
{
	
	public void OnGetAsync()
	{
		BookingService bookingService = new BookingService();
		List<Stock> _stocks = await bookingService.GetStockDetails();
		StockList = _stocks;   
		
	}
}

But there is another better way to write the same function.

async property in razorpage get - working

Now to make above async page onget method working properly, we need to change the return type from void to Task<IActionResult>, and Additionally, add a return statement at the end return Page();.

[BindProperties]
public class stockupdateModel : PageModel
{
	[BindProperty]
	public List<Stock> StockList { get; set; }


	public async Task<IActionResult> OnGet()
	{
		BookingService bookingService = new BookingService();
		List<Stock> _stocks = await bookingService.GetStockDetails();
		StockList = _stocks;
	   
		return Page();
	}
}

Now if you try to access the property StockList in your razor view, you will see all data are loaded properly, here is the example of how code will look like.

@{
   List<Stock> _stocks = Model.StockList;
   
    if (_stocks != null)
    {
        foreach (Stock s in _stocks)
        {
            <div class="row">
                <div class="col-md-2">
                    @s.Product
                </div>
                <div class="col-md-2">
                    @s.Price
                </div>
                <div class="col-md-2">
                    @s.Qty
                </div>
                <div class="clearfix"></div>
            </div>
        }
    }
}

Make sure you have added BindProperty and BindProperties attributes properly in your PageModel class.

You should also read following post to learn more about PageModel, Handler Methods, leveraging Model Binding, Handler method parameters etc.


Asp.Net Core C# Examples | Join Asp.Net MVC Course