Apply Permission On Buttons

Mahdi Elahi 31 Reputation points
2022-03-19T07:16:48.673+00:00

Hi,
i used permission based in my project
in the index page , i show list of books with buttons (edit,delete,details)
184743-capture.png

but how to apply permissions on these button ,that's means
when a user don't have delete permission then in the index page don't show delete button

i use this way to apply permission for buttons

 <tbody>  
            @foreach (var item in Model)  
            {  
            <tr >  
             
                <td>  
                    @Html.DisplayFor(modelItem => item.Title)  
                </td>  
               
                <td>  
                    if(@_userService.UserHasPermission("Update"))  
                    {  
                    <a href="/Books/Edit/@item.Id"></a>  
                    }  
                    
                </td>  
            </tr>  
  
            }  
        </tbody>  

but the UserHasPermission call every time because it's call in foreach(execute query every time )

It is not interesting and optimal

is there any way to apply permission on buttons ?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,141 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2022-03-19T15:37:50.913+00:00

    A standard optimization is to extract calculation of constants out of the loop

                 @var updatePermission = _userService.UserHasPermission("Update"));
                 foreach (var item in Model)
                 {
                 <tr >
    
                     <td>
                         @Html.DisplayFor(modelItem => item.Title)
                     </td>
    
                     <td>
                         @if(updatePermission))
    
    0 comments No comments