Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created May 28, 2019 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielplawgo/ac4d58837224dba7b6fc51de865b12da to your computer and use it in GitHub Desktop.
Save danielplawgo/ac4d58837224dba7b6fc51de865b12da to your computer and use it in GitHub Desktop.
Blazor JavaScript Interop
@page "/fetchdata"
@using CsvHelper
@using System.IO
@using System.Text
@inject IWeatherForecastService Service
@inject IFileService FileService
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<button onclick="@Download">Download</button>
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@functions {
WeatherForecast[] forecasts;
protected override async Task OnInitAsync()
{
forecasts = await Service.GetAsync();
}
void Download()
{
using (var writer = new StringWriter())
{
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(forecasts);
FileService.SaveAsAsync("data.csv", Encoding.ASCII.GetBytes(writer.ToString()));
}
}
}
}
public class FileService : IFileService
{
private IJSRuntime _jsRuntime;
public FileService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public Task SaveAsAsync(string filename, byte[] data)
{
return _jsRuntime.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}
}
public interface IFileService
{
Task SaveAsAsync(string filename, byte[] data);
}
<script type="text/javascript">
function saveAsFile(filename, bytesBase64) {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment