0

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.

mxmissile
  • 11,464
  • 3
  • 53
  • 79
  • 2
    Why you want use input hidden, when a variable in component (or page) can save your value? – mRizvandi Feb 23 '22 at 16:02
  • I need a way to bring in the currentUser into that value, and bind it to createdBy. Thats my goal anyway.

    CurrentUser

    Will display current user in component. now I am looking to bind that to the createdby property

    – That Noob Programmer Feb 23 '22 at 16:12
  • Ok, if I understand your request, you have to set user in your controller, not in Blazor, because of security reason. – mRizvandi Feb 23 '22 at 16:21
  • 1
    So this is my current solution, however I am not sure if its secure anymore. Project projectObject = new Project(); protected async override Task OnInitializedAsync() { var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync(); projectObject.CreatedBy = authstate.User.Identity.Name; } Then Just changed createdby in database to string. So is that no longer secure...? – That Noob Programmer Feb 23 '22 at 16:29
  • No, its not secure, you have to set the projectObject.CreatedBy on server side, sample code: var user = await UserManager.FindByEmailAsync(HttpContext.User.Identity.Name); project.CreatedBy = user.Id; – mRizvandi Feb 23 '22 at 20:31

1 Answers1

0

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! Hope it helps you and welcome to StackOverflow!

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

Leandro Toloza
  • 1,655
  • 1
  • 6
  • 24