Reputation: 139
I'm trying to hide menu options from navbar
in master page based on user roles
but when I tried to call the element it gives me an error.
This is what I did :
MasterPage
<div class="navbar-collapse collapse">
<ul id="MasterMenu" class="nav navbar-nav">
<li id="liDashboard">
<a runat="server" href="~/_Dashboard">Dashboard</a>
</li>
<li id="liTicket">
<a runat="server" href="~/Forms/Tickets/_Ticket">Ticket+</a>
</li>
<li id="liReports">
<a runat="server" href="-">Reports</a>
</li>
</ul>
</div>
And in another page
if (User.IsInRole("User"))
{
System.Web.UI.HtmlControls.HtmlGenericControl liDashboard = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("liDashboard");
liDashboard.Visible = false;
}
Also I tried to add runat="server"
but it still not working.
Upvotes: 2
Views: 2240
Reputation: 1720
For example if your place holder something like that.
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
Try to use something like that
Master.FindControl("MainContent").FindControl("liDashboard")
Then find your value hierarchically
And of course values need to be with runat="server"
Edit
Give your PlaceHolder
an ID
<asp:PlaceHolder ID="Something" runat="server"/>
and get your value with:
Master.FindControl("Something").FindControl("liDashboard")
Upvotes: 0
Reputation: 39966
Use Null-Conditional operator (?.
) and check for null before assignment:
System.Web.UI.HtmlControls.HtmlGenericControl liDashboard =
(System.Web.UI.HtmlControls.HtmlGenericControl)Master?.FindControl("liDashboard");
if (liDashboard != null) liDashboard.Visible = false;
Also you have missed runat="server"
in the following line:
<li id="liDashboard" runat="server">
Upvotes: 3