ASP.NET Hide/disable entire dropdown menu based on user role - c#

I have a drop-down list in an ASP.NET webform application generated in the sitemaster menu using the follow ing code:
<li class="dropdown" id="Admin" > <a class="dropdown-toggle" data-toggle="dropdown" href="#">Admin<span class="caret" ></span></a>
<ul class="dropdown-menu" >
<li><a runat="server" href="~/Admin/Members">Members Management</a></li>
<li ><a runat="server" href="~/Admin/MembersRegistry">Members Registry</a></li>
</ul>
</li>
and the script to generate the drop down is
<script>
$(document).ready(function () {
$(".dropdown").hover(function () {
//toggle the open class (on/off)
$(this).toggleClass("open");
});
})
</script>
I want to be able to hide or show the entire dropdown menu based on user roles:
protected void Page_Load(object sender, EventArgs e)
{
Admin.Visible = false;
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
var user = HttpContext.Current.User.Identity.GetUserId();
if (manager.IsInRole(user, "Admin"))
{
Admin.Visible = true;
}
}
}
But this is not working and the Admin control is not accessible from the code behind, any thoughts or suggestions please?

If you add a runat="server" tag to that, then your code behind should see/have use of that controls, and you code looks like it should work ok.
eg:
<li class="dropdown" id="Admin" runat="server">
.etc. etc.
</li>

Related

Inserting items into bootstrap-dropdown from SQL Table

I am working on asp.net project and my code behind language is c#. I have one bootstrap dropdown in which i want to get the items from SQL Table. is there anyone who will help me in this regard. thanks in advance.
<li class="nav-item dropdown">
<a class="btn btn-light dropdown-toggle" href="#" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Category
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
Action, Another Action and Something else items should come from database (Category) Table. Using c# language on server side is much appreciable.
There are some ways to do it in WebForms, but first you need to make the DIV element of the dropdown menu accessible from the Code Behind.
See this snippet?
<ul class="nav nav-tabs">
<li class="nav-item dropdown">
<a class="btn btn-light dropdown-toggle" href="#" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Category
</a>
<div id="myDropdownMenu" runat="server" class="dropdown-menu" aria-labelledby="navbarDropdown">
</div>
</li>
</ul>
Note that I added 2 attributes : id="myDropdownMenu" and runat="server".
After this you can go to Code Behind to start populating the menu from a data source.
At least there are 2 ways to do this, as far as I know.
By manipulating the InnerHtml property, like this :
private void DisplayMenuByConstructingHtmlTags(List<string> menuList)
{
var menuHtml = "";
foreach (string menuText in menuList)
{
menuHtml += "<a class=\"dropdown-item\" href=\"#\">" + menuText + "</a>\n";
}
myDropdownMenu.InnerHtml = menuHtml;
}
Or, by adding the menu as the child controls, like this :
private void DisplayMenuByAddingChildControls(List<string> menuList)
{
foreach (string menuText in menuList)
{
var linkMenu = new HyperLink() { CssClass = "dropdown-item", NavigateUrl = "#", Text = menuText };
myDropdownMenu.Controls.Add(linkMenu);
}
}
It's your call, which one to choose.
Btw, just to complete this example, you may try to call one of those methods from the Page_Load event, like this :
EDIT :
By your request, I've modified the samples by adding a connection to a table in a database. So, this is the module to load the data :
private List<string> LoadMenuFromTable()
{
string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ToString();
var retVal = new List<string>();
using (var connection = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand("SELECT menu_text FROM Table_1", connection))
{
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
retVal.Add((string)reader["menu_text"]);
}
}
}
}
return retVal;
}
And here's how you should call the module :
protected void Page_Load(object sender, EventArgs e)
{
var menu = LoadMenuFromTable();
DisplayMenuByAddingChildControls(menu);
// or DisplayMenuByConstructingHtmlTags(menu);
}
Oh, and remember to import these two libraries to make this sample works :
using System.Configuration;
using System.Data.SqlClient;
Hope it helps.

Show/Hide href link on click on a button

On a BUTTON click a detail page is generated.
I have a href link when click on it, it navigates in the page.
But on page load there should be only the button (on Clicking it main page is generated) but the href link is also appearing.
I want on the page load there should be only one button by clicking on it href link should appear.
And should disappear when another button is clicked.
Scrip:
$(document).ready(function () {
$('#priorityC').hide();
$('#perC').hide();
});
$('#btnAnalyse').click(function () {
$('#priorityC').show();
$('#perC').show();
});
This is the button:
<asp:ImageButton ID="btnAnalyse" runat="server" OnClick="btnAnalyse_Click"/>
This is the href link which i want to show only on the click of the above button:
Hourly Detailed Priority Representation
<a name="priorityPer">
<div id="perC" class="center">
<asp:Label ID="lblDPTC" runat="server" Text="Detailed Percentage representation of Ticket Count" Visible="false"></asp:Label>
</div>
</a>
Its hiding on page load but not showing on button click.
<asp:ImageButton ID="btnAnalyse" runat="server" ImageUrl="image1.jpg" OnClick="btnAnalyse_Click"/>
Hourly Detailed Priority Representation
<a name="priorityPer">
<div id="per" class="center">
<asp:Label ID="lblDPTC" runat="server" Text="Detailed Percentage representation of Ticket Count" Visible="false"></asp:Label>
</div>
</a>
and on your backend page( codepage.cs)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
linkid.Visible = false;
}
}
protected void btnAnalyse_Click(object sender, ImageClickEventArgs e)
{
if (linkid.Visible == false)
{
linkid.Visible = true;
}
}
protected void btnAnother_Click(object sender, EventArgs e)
{
linkid.Visible = false;
}
You can write your href link inside a div and using Jquery, you can hide and show the the div accordingly.
Code snippet
<script>
// On load hide the div
$(document).ready(function(){
$('#MYDIV').hide();
};
// call this function on button click to show/hide the link
function showHideLink(buttonName)
{
if(buttonName=='blah')
{
$('#MYDIV').hide();
}
else
{
$('#MYDIV').show();
}
}
</script>
Hope this helps.
test.aspx
<li class="nav-item">
<a class="nav-link" id="AdminFaciliy" href="charts.html" runat="server">
<i class="fas fa-fw fa-user">
</i>
text.aspx.cs
if (Utype.Trim().ToUpper()=="ADMIN"){
AdminFaciliy.Visible = true;
}

Dynamically add the menu based on session value in asp.net

I am working on a project where i have to show different menu based on username
i have added the menu in master page
The code is
<ul id="ul_myLst" runat="server">
<li>Testimonial</li>
<li>About Us</li>
<li>Registartion</li>
<li id="student" runat="server" visible="false">
profile
<ul>
<li>
View profile
</li>
<li>
Edit profile
</li>
</ul>
</li>
<li id="abc" runat="server" visible="false" >Admin</li>
<li id="Li1" runat="server" visible="false" >Reports</li>
</ul>
where i want to show three hidden value when user logged in as "admin"
here is my .cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Session["UserName"] as string))
{
admin();
}
}
private void admin()
{
if (Session["UserName"].ToString() == "admin")
{
HtmlGenericControl ul = (HtmlGenericControl)(this.FindControl("abc"));
ul.Style["visibility"] = "visible";
}
}
This code is not giving me any error but it's also not showing me the desired output..
You can hide and show it this way:
ul.Style.Add("visibility","visible"); // for showing
ul.Style.Add("display","block");
and for hiding:
ul.Style.Add("visibilty","hidden"); // for hiding
ul.Style.Add("display","none");
Try using display property :
ul.Style.Add("display", "none");
Since your control has an id and runat="server", you may also use :
abc.Visible = false;
visible="false" does not touch an element's style at all. This is setting the Control.Visible property of the control you are manipulating. When this property is set to false, the control is not rendered to the page at all - it is just absent on the final markup. So on the server side you actually want this in admin method:
ul.Visible = true;
Use this code
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Session["UserName"] as string))
{
admin();
}
}
private void admin()
{
if (Session["UserName"].ToString() == "admin")
{
this.Page.FindControl("abc").Visible = true;
}
}
If you use in Master page then use this code
private void admin()
{
if (Session["UserName"].ToString() == "admin")
{
this.Master.FindControl("abc").Visible = true;
}
}
thanks

Link <a href="..."/> is not working in nopcommerce in submenu

I am new to NopCommerce and I want to add submenu in my store.
I have added my submenu, but when I click on it, the link which I have given in is not working and it gives me an error.
My code is as below:
Menu View File
<li id="DevelopmentItem">
Development
<ul id="Developmentsubmenu" class="dropdown-ul">
**<li>NPC Development</li>
<li>NPC Extension Development</li>
<li>NPC Customize</li>**
</ul>
</li>
<script type="text/javascript">
$('#DevelopmentItem').live('mouseenter', function () {
$('#Developmentsubmenu').addClass('active');
});
$('#DevelopmentItem').live('mouseleave', function () {
$('#Developmentsubmenu').removeClass('active');
});
</script>
CommonController.cs file
public ActionResult NpcDevelopment()
{
return View();
}
NpcDevelopment View File
#{
ViewBag.Title = "NpcDevelopment";
Layout = "~/Views/Shared/_ColumnsOne.cshtml";
}
<h2>NpcDevelopment</h2>
I can't find my fault. Can anyone help me?
Are you using mvc3 to develop? If you are, replace
<a href="~/Common/NpcDevelopment"> with this
<a href="#Url.Action("{Action}", "{Controller}")">for example:
<a href="#Url.Action("NpcDevelopment", "Common")">

How can i make a div as non selectable from code behind

I have my div as follows
<div class="menu" id="admindiv" runat="server">
<ul>
<li>welcome to my site<!--[if IE 7]><!--><!--<![endif]-->
<table>
<tr>
<td>
<ul>
<li>Reports</li>
<li>Delete</li>
</ul>
</td>
</tr>
</table>
<!--[if lte IE 6]></a><![endif]-->
</li>
<!--[if lte IE 6]></a><![endif]-->
</ul>
</div>
I would like to enable or disable on a page from code behind, means i would like to make this div as non selectable field on certain conditions. I tried this but i didn't get succeeded
protected void Page_Load(object sender, EventArgs e)
{
admindiv.Attributes.Add("style", "color:gray;");
admindiv.Attributes.Add("disabled", "true");
}
You can't make a DIV non-selectable. If you want to make the links non-clickable, this is the code-snipt does it:
<div class="menu" id="admindiv">
<ul>
<li>welcome to my site<!--[if IE 7]><!--><!--<![endif]-->
<table>
<tr>
<td>
<ul>
<li>
<asp:HyperLink ID="Link1" runat="server" Text="Reports" />
</li>
<li>
<asp:HyperLink ID="Link2" runat="server" Text="Delete" />
</li>
</ul>
</td>
</tr>
</table>
<!--[if lte IE 6]></a><![endif]-->
</li>
<!--[if lte IE 6]></a><![endif]-->
</ul>
</div>
AND the code-behind:
protected void Page_Load(object sender, EventArgs e) {
if(isAdmin) { // check for admin user
Link1.NavigateUrl = "Reports.aspx";
Link1.NavigateUr2 = "Delete.aspx";
} else {
Link1.NavigateUrl = "javascript:return void;";
Link1.NavigateUr2 = "javascript:return void;";
}
}
Divs can be shown and hidden, but not disabled. If the div is visible its contents will be active unless you disable each item individually.
Another option to disabling each control is to create a new div that is transparent but sits on top of the part you want to disable, then just show / hide that div from the code behind.
However this is not a security mechanism, as anyone with a browser HTML developer plug-in (like firebug) can remove that div and gain access to the controls.
The best way to disable links in ASP.NET is to add an "onclick" event (works with linkbuttons and hyperlinks):
LinkButton1.Attributes["OnClick"] = “return false;”;

Categories