|
| 1 | +@using Microsoft.JSInterop |
| 2 | +@inject IJSRuntime JSRuntime |
| 3 | + |
| 4 | +<button id="btn-interop" @onclick="InvokeInteropAsync">Invoke interop!</button> |
| 5 | + |
| 6 | +<p> |
| 7 | + This component shows it's possible to save and load value types (in this case, a guid) |
| 8 | + to and from localstorage, |
| 9 | + and also that a null value can be loaded into a nullable value type, i.e. a Guid?. |
| 10 | +</p> |
| 11 | + |
| 12 | +<p> |
| 13 | + String value from guid: |
| 14 | + <strong id="string-get-by-interop">@(StringFromInterop ?? "No value yet")</strong> |
| 15 | +</p> |
| 16 | + |
| 17 | +<p> |
| 18 | + Guid value from guid is default(Guid) if it wasn't loaded correctly: |
| 19 | + <strong id="guid-get-by-interop">@GuidFromInterop</strong> |
| 20 | +</p> |
| 21 | + |
| 22 | +<p> |
| 23 | + Nullable Guid value from guid is null if it wasn't loaded correctly: |
| 24 | + <strong id="nullable-guid-get-by-interop">@NullableGuidFromInterop</strong> |
| 25 | +</p> |
| 26 | + |
| 27 | +<p> |
| 28 | + Nullable load result is false if the null value wasn't loaded into the nullable guid correctly: |
| 29 | + <strong id="null-loaded-into-nullable">@NullableLoadResult</strong> |
| 30 | +</p> |
| 31 | + |
| 32 | +@if (DoneWithInterop) |
| 33 | +{ |
| 34 | + <p id="done-with-interop"> |
| 35 | + Done with interop! |
| 36 | + </p> |
| 37 | +} |
| 38 | + |
| 39 | +@code { |
| 40 | + public Guid Guid { get; } = Guid.NewGuid(); |
| 41 | + public string StringFromInterop { get; set; } |
| 42 | + public Guid GuidFromInterop { get; set; } |
| 43 | + public Guid? NullableGuidFromInterop { get; set; } |
| 44 | + public bool NullableLoadResult { get; set; } |
| 45 | + public bool DoneWithInterop { get; set; } |
| 46 | + |
| 47 | + private async Task InvokeInteropAsync() |
| 48 | + { |
| 49 | + // Store guid in localStorage |
| 50 | + await JSRuntime.InvokeVoidAsync("localStorage.setItem", "guid", Guid); |
| 51 | + |
| 52 | + // Retrieve guid from localStorage as string because it's a simple conversion |
| 53 | + StringFromInterop = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "guid"); |
| 54 | + |
| 55 | + // Retrieve guid from localStorage as Guid |
| 56 | + GuidFromInterop = await JSRuntime.InvokeAsync<Guid>("localStorage.getItem", "guid"); |
| 57 | + |
| 58 | + // Retrieve guid from localStorage as Guid? |
| 59 | + NullableGuidFromInterop = await JSRuntime.InvokeAsync<Guid?>("localStorage.getItem", "guid"); |
| 60 | + |
| 61 | + // Retrieve null from localStorage as Guid? |
| 62 | + var nullableGuid = await JSRuntime.InvokeAsync<Guid?>("localStorage.getItem", "nothingHere"); |
| 63 | + |
| 64 | + // If the retrieval crashes, the bool stays false |
| 65 | + NullableLoadResult = !nullableGuid.HasValue; |
| 66 | + |
| 67 | + DoneWithInterop = true; |
| 68 | + } |
| 69 | +} |
0 commit comments