Hi @Anthony ,
For the in-memory objects, you can use System.Text.Json.JsonSerializer.Serialize()
method to convert the objects to the json string, then convert the string to byte array using the System.Text.ASCIIEncoding.ASCII.GetBytes()
method, after that you can also use the File()
method to export the data to a json file.
Code as below:
Download Razor page:
Download.cshtml:
@page "/download"
@model BlazorServerSample.Pages.DownloadModel
@{
}
Download.cshtml.cs:
public class DownloadModel : PageModel
{
private readonly IWebHostEnvironment _env;
private readonly WeatherForecastService _forecastService;
public DownloadModel(IWebHostEnvironment env, WeatherForecastService weatherForecastService)
{
_env = env;
_forecastService = weatherForecastService;
}
public async Task<IActionResult> OnGetAsync()
{
//get forecast from forecast service
var forecasts = await _forecastService.GetForecastAsync(DateTime.Now);
var jsonstr = System.Text.Json.JsonSerializer.Serialize(forecasts);
byte[] byteArray = System.Text.ASCIIEncoding.ASCII.GetBytes(jsonstr);
return File(byteArray, "application/force-download", "file1.json");
}
}
The WeatherForecast class:
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
In the main page, add the following download button:
<a class="form-control btn btn-primary" href="/download">Download</a>
The result as below:
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion