Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.Net MVC Hide/Show Menu Items Based On Security
    primarykey
    data
    text
    <p>I'm working on an ASP.Net MVC 3 site. The _Layout master view contains a menu and I want to hide some of the items in the menu based on if you are logged in and what roles you are in.</p> <p>This currently works using code like this</p> <pre><code>@if (HttpContext.Current.User.Identity.IsAuthenticated) { &lt;li id="MyLearningTab"&gt;@Html.ActionLink("My Learning", "MyLearning", "Learning")&lt;/li&gt; if (HttpContext.Current.User.IsInRole("Reporters")) { &lt;li id="ReportTab"&gt;@Html.ActionLink("Reports", "Index", "Reports")&lt;/li&gt; } if (HttpContext.Current.User.IsInRole("Administrators")) { &lt;li id="DashboardTab"&gt;@Html.ActionLink("Dashboard", "Dashboard", "Admin")&lt;/li&gt; &lt;li id="AdminTab"&gt;@Html.ActionLink("Admin", "Index", "Admin")&lt;/li&gt; } } </code></pre> <p>I'd like to refactor this in to something more readable and came up with something like this</p> <pre><code>@if ((bool)ViewData["MenuMyLearning"]){&lt;li id="MyLearningTab"&gt;@Html.ActionLink("My Learning", "MyLearning", "Learning")&lt;/li&gt; } @if((bool)ViewData["MenuReports"]){&lt;li id="ReportTab"&gt;@Html.ActionLink("Reports", "Index", "Reports")&lt;/li&gt;} @if ((bool)ViewData["MenuDashboard"]){&lt;li id="DashboardTab"&gt;@Html.ActionLink("Dashboard", "Dashboard", "Admin")&lt;/li&gt;} @if ((bool)ViewData["MenuAdmin"]){&lt;li id="AdminTab"&gt;@Html.ActionLink("Admin", "Index", "Admin")&lt;/li&gt;} </code></pre> <p>I originally added the following to my base controller constructor thinking I could setup the ViewData for these properties there</p> <pre><code>ViewData["MenuDashboard"] = User != null &amp;&amp; User.Identity.IsAuthenticated &amp;&amp; User.IsInRole("Administrators"); ViewData["MenuAdmin"] = User != null &amp;&amp; User.Identity.IsAuthenticated &amp;&amp; User.IsInRole("Administrators"); ViewData["MenuReports"] = User != null &amp;&amp; User.Identity.IsAuthenticated &amp;&amp; User.IsInRole("Reportors"); ViewData["MenuMyLearning"] = User != null &amp;&amp; User.Identity.IsAuthenticated; </code></pre> <p>However it turns out the User object is null at this point in the lifecycle. I've also tried creating a custom global filter but the ViewData is then not accessable.</p> <p>What is the recommended way of doing something like this? Should I just leave it how it was at first with all the HttpContext code in the view?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload