Zapnologica
Zapnologica

Reputation: 22556

Blazor render specific content based on roles

I have a table where I am looping through my model of row items. I want to show a delete button to users who are in the Role: Admin. How do I do this in Blazor?

I have tried

 <AuthorizeView Roles="Admin">
              <MudButton> ADMIN ONLY BUTTON</MudButton>
 </AuthorizeView>

Now, this all seems to work fine, except for the fact that the AuthorizeView changes my context. So I now lose reference to the Model which I am working on, so Now I want to add an OnClick Listener to redirect to device/delete/{@contenxt.DeviceId} and VS now moans to say the context does not have a reference to DeviceId

Upvotes: 0

Views: 2755

Answers (2)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30001

This answer is making an assumption - AuthorizedView is a type and you mean AuthorizeView and not some custom AuthorizedView component.

AuthorizeView sets the context for it's content to the current AuthenticationState. Hence {@contenxt.DeviceId} doesn't work - there's no DeviceId on AuthenticationState.

As you haven't show much "context" for your question - apologies for the pun! - I'm assuming you're iterating through a list and showing an edit button for each record. If so, you can set a local loop variable to your context outside AuthorizeView and then refer to that in your button call.

Something like:

@{
    var device = context;
}
 <AuthorizedView Roles="Admin">
              <MudButton @onclick="() => GotToEdit(device.DeviceId)"> ADMIN ONLY BUTTON</MudButton>
 </AuthorizedView>

Upvotes: 2

Brian Parker
Brian Parker

Reputation: 14523

Rename one of the contexts to avoid the conflict:

<AuthorizedView Roles="Admin" Context="SomeOtherName" >
              <MudButton> ADMIN ONLY BUTTON</MudButton>
</AuthorizedView>

Upvotes: 2

Related Questions