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

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

Related

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

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>

How can update usercontrol in masterpage

I have a master page and an user control on it.
I have a two buttons in the user control for create or remove session, and a label that shows a session text, when click the buttons nothing happens and user control doesn't update I should refresh the page,
Would you please anybody help me to fix this issue ?
This is my master page markup:
<form runat="server">
<div>
<!--previous codes-->
<nav class="navigation">
<div class="wrapper">
<controller:menu runat="server" ID="menu" />
<controller:user runat="server" ID="user" />
</div>
</nav>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<!--Next Codes-->
</div>
</form>
and this is my user control
<ul class="nav signup">
<li class="no-drop-down">
<asp:Label ID="_signupbutton" runat="server" CssClass="sr">Test</asp:Label>
<div class="signup-dropdown">
<asp:PlaceHolder ID="_defaultuser" runat="server" Visible="false">
<div class="notloggeduser">
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="usercontroller"
OnClick="LinkButton1_Click" Text="????">
</asp:LinkButton>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="_signedup" runat="server" Visible="false">
<div class="defaultuser">
<ul>
<li>
<asp:LinkButton ID="_userlogout" runat="server" CssClass="usercontroller" OnClick="_userlogout_Click">
<i class="fa"></i>????
</asp:LinkButton>
</li>
</ul>
</div>
</asp:PlaceHolder>
</div>
</li>
</ul>
and this is user control codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["signup"] == null)
{
_signupbutton.Text = "??? ??? / ????";
_defaultuser.Visible = true;
}
else
{
_signupbutton.Text = "<i class=\"fa\"></i> " + Session["signup"].ToString();
_signedup.Visible = true;
}
}
}
protected void _userlogout_Click(object sender, EventArgs e)
{
Session.Remove("signup");
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session.Add("signup", "????? ??????????");
}
Your order of events is a bit messed up here.
Page_Load will execute before the event handlers for the click events. You need to perform the setup of the button state from the event handlers, as if you do it in page load your session object wont have been updated yet.
You will need to do a few things here (this isn't tested but should show you the logic):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // This will run when the page is loaded but not from a post back / button click etc (e.g. from your page refresh)
{
this.SetButtonState();
}
else
{
// use this for things you want to happen on postback only
}
}
private void SetButtonState()
{
if (Session["signup"] == null)
{
_signupbutton.Text = "??? ??? / ????";
_defaultuser.Visible = true;
}
else
{
_signupbutton.Text = "<i class=\"fa\"></i> " + Session["signup"].ToString();
_signedup.Visible = true;
}
}
protected void _userlogout_Click(object sender, EventArgs e)
{
Session.Remove("signup");
// Update your button state
this.SetButtonState();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session.Add("signup", "????? ??????????");
// Update your button state
this.SetButtonState();
}

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;
}

Repeater and Custom Control - Dynamically adding to the collection and retaining values

It has been so long since I've used Web Forms I find myself not remembering most of the perks.
I have a user control that has a button, a repeater and the ItemTemplate property of the repeater is another user control.
<asp:Button runat="server" ID="btnAdd" CssClass="btn" Text="Add" OnClick="btnAdd_Click"/>
<br/>
<asp:Repeater runat="server" ID="rptrRequests">
<ItemTemplate>
<uc1:ucRequest ID="ucNewRequest" runat="server" />
</ItemTemplate>
</asp:Repeater>
The idea is that when the user clicks on the Add button a new instance of the ucRequest is added to the collection. The code behind is as follows:
public partial class ucRequests : UserControl
{
public List<ucRequest> requests
{
get
{
return (from RepeaterItem item in rptrRequests.Items
select (ucRequest) (item.Controls[1])
).ToList();
}
set
{
rptrRequests.DataSource = value;
rptrRequests.DataBind();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
requests = new List<ucRequest>();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = requests;
reqs.Add(new ucRequest());
requests = reqs;
}
}
After much googling I now remember that I should be binding the Repeater in the OnInit method in order for the ViewState to put the captured data of the controls within the ucRequest control on them between post backs but when I try to do that I will always have a single instance of the control on the Repeater since its Items collection is always empty.
How could I manage to do this?
Thanks in advance.
You just need control ids in view state stead of entire control collection.
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="ucRequests.ascx.cs"
Inherits="RepeaterWebApplication.ucRequests" %>
<asp:Button runat="server" ID="btnAdd" CssClass="btn" Text="Add"
OnClick="btnAdd_Click" />
<br /><asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="ucRequest.ascx.cs"
Inherits="RepeaterWebApplication.ucRequest" %>
<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>) ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (int id in ControlIds)
{
Control ctrl = Page.LoadControl("ucRequest.ascx");
ctrl.ID = id.ToString();
PlaceHolder1.Controls.Add(ctrl);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
Control ctrl = Page.LoadControl("ucRequest.ascx");
ctrl.ID = id.ToString();
PlaceHolder1.Controls.Add(ctrl);
}
Try to get the ucRequests during the OnItemDatabound event, at that point you can edit the content of itemtemplate of the repeater. You can get there after the postback caused by the click on the add button. Here's a sample with a similar scenario

Panel with in Listview gives me an error(Object reference not set to an instance of an object.)

I have a panel in Itewmtemplate of list view it's only supposed to show when user is logged in, by default the visibility = false. Help is appreciated.
here is my c# code:
Panel pnlOptions = (Panel)ListView1.FindControl("pnlOptions");
pnlOptions.Visible = true;
Aspx Code:
<asp:Panel ID="pnlOptions" runat="server" Visible="false">
<ul>
<ul>
<li style="float: left">Option 1:</li>
<li style="float: left">dropdown here</li>
</ul>
<li style="float: left">Option 1:</li>
<li style="float: left">dropdwon here</li>
</ul>
</asp:Panel>
You're getting the error because the FindControl call is either:
Failing - If the item is not found as a child of the control, FindControl returns null.
Finding the "wrong" object, and the cast to (Panel) is failing.
I'd recommend rewriting the code as:
Control control = ListView1.FindControl("pnlOptions");
Panel pnlOptions = control as Panel;
pnlOptions.Visible = true;
You can then set breakpoints, and figure out which of the lines is failing on you.
My problem was I was trying to acces it wrongly through a function I created when I was supposed to use the Item_Created Event here is the final working code:
protected void ListView1_ItemCreated(object sender, ListViewItemEventArgs e)
{
Control control = e.Item.FindControl("pnlOptions");
Panel pnlOptions = control as Panel;
pnlOptions.Visible = true;
}
Thanks Reed.
This should work also:
foreach (var item in ListView1.Items)
{
Panel pnlOptions = (Panel)item.FindControl("pnlOptions");
pnlOptions.Visible = true;
}

Categories