'Blazor Server Side - sharing values from Parent (Mainlayout) to Child Component (Pages)
Good Day everyone
On my project, I have created a simple cookie authentication, now on my MainLayout.razor, and created a separate code file (MainLayout.razor.cs), now on the code file, I put a code that gets the authenticated user.
var AuthState = await authenticationStateProvider.GetAuthenticationStateAsync();
var GetUser = AuthState.User;
string strUser = AuthState.User.Claims.First().Value.ToString();
EmpDetails GetEmpDetails = myServices.GetUserDetails(strUser)
Now, I want the GetEmpDetails to share it with the child components, my current setup is, I have to call this code again on each page, Is there a way to share this from Parent to Child components?
Thanks and regards
Solution 1:[1]
Add class like
public class DataService
{
public Dictionary<string, EmpDetails> EmpDetails { get; set; }
}
register service in Program.cs, it may be Startup.cs
builder.Services.AddSingleton<DataService>();
now in MainLayout
[Inject]
private DataService DataService { get; set; }
if (DataService.EmpDetails.ContainsKey(EmpLoginId))
DataService.EmpDetails.Remove(EmpLoginId);
DataService.EmpDetails.Add(EmpLoginId, EmpDetails);
Now in any blazor component
[Inject]
private DataService DataService { get; set; }
and you can get user like
var empDetails = DataService.EmpDetails[EmpLoginId];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
