In my _Layout.cshtml I have the following code which will not show the buttons if the user's role is UserType1
@if (!(HttpContext.Current.User.IsInRole("UserType1")))
{
<li><a href="../St/Index">Static</a> </li>
<li><a href="../St/Clients">Clients</a> </li>
}
I was wondering if there is a better or best practice way of doing this. Please note that I am putting this code in my _Layout.cshtml file.
This seems fine. Some people (like me) might prefer to bring this a step further and wrap this check in a custom HTML helper though in order to be able to unit test the condition:
@if (Html.ShouldShowButtons())
{
<li><a href="../St/Index">Static</a> </li>
<li><a href="../St/Clients">Clients</a> </li>
}
and the implementation of the helper:
public static class HtmlExtensions
{
public static bool ShouldShowButtons(this HtmlHelper html)
{
return html.ViewContext.HttpContext.User.IsInRole("UserType1");
}
}
As an alternative you could implement more complex logic using child actions:
@{Html.RenderAction("MenuButtons", "Menu");}
You would then have a corresponding controller action which is checking whether the user is in the required role and render a partial view with the markup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With