Search code examples
c#entity-frameworkasp.net-identityblazor.net-6.0

Blazor Hidden input bind to Identity User


As Title states, I would like to bind IdentityUser Properties to a hidden form input. Or perhaps I am going about the wrong way. It is tracking who creates a new project. I have access to Identity and properties.

Here is an example of my form taking in an input. Project Target End Date: <input type="datetime-local" @bind="projectObject.TargetEndDate">

This is an example of what id like to have happen

    <input type="hidden" @bind="projectObject.CreatedBy"> 

(Take in IdentityUser some how here)

Here is my property binding. Project projectObject = new Project();

string CurrentUser { get; set; }

protected async override Task OnInitializedAsync()
{
    var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync();
    CurrentUser = authstate.User.Identity.Name;        
}

I would like to bind CurrentUser to CreatedBy. Coding answer would appreciated, however I would like to read about the answer as well.


Solution

  • If i understand properly your problem the solution should be like this

    @code{
        Project projectObject = new Project();
        protected async override Task OnInitializedAsync()
        {
            var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync();
            projectObject.CreatedBy = authstate.User.Identity.Name;
        }
    }
    

    So in this way, everytime you open the form, and the component initialized, you will save the current user on the created by property. And You didn't need to create the input hidden value!

    And if in your component doesn't work, check this solution from another user using IHttpContextAccessor