show html elements based on user's role - c#

I am trying to hide html elements from plain users such that only users.
I have simple asp.net web form setup that makes use of roles provider and membership.
<li runat="server" id="li1" visible ='<%# HttpContext.Current.User.IsInRole("admin") %>'><span> Admin link</span></li>
I also am trying this without success:
<li runat="server" id="liAdminUsers" visible ='<%# isAdmin %>'><span> The Hopper</span></li>
the code behind is:
public bool isAdmin =false;
protected void Page_Load(object sender, EventArgs e)
{
isAdmin = Page.User.IsInRole("admin");
}
update: I know I can get it working by adding in the code behind:
liAdminUsers.Visible = false ;
but want a UI solution in the .aspx code

You are using data-binding syntax <%# ... %>, so you need to call Page.DataBind()
You typically call DataBind() in your Page_Load method.

I once did something similar using a custom XML file with an attribute indicating if roles were applied or not for a particular application link - and if so, another attribute containing the role name. The code-behind would then check the custom membership store using the logged-in users network identity for authorization checking.

Write a static method in code behind to test the role
public static bool IsAdmin(){
//chech and return true or false
}
In html call this method like
<li runat="server" id="liAdminUsers" visible ='<%# isAdmin() %>'>.....</li>
In this way you can control you logic like any other method.
Or you can directly set element visible false in your code behind
public static void IsAdmin(){
var admin = ....; //check current user role;
liAdminUsers.Visible = admin;
}

I suggest you formulate a class that will hide the said elements.
CSS
hide-elements {
display:none;
}
show-elements {
display:block;
}
C# CodeBehind
public string isAdmin()
{
if (condition == false)
return "hidden-elements";
else
return "show-elements";
}
HTML code
<li runat="server" id="liAdminUsers" class='<%# isAdmin() %>'>.....</li>
Hope this help. :D (my first post)

If you are reaching a variable from code behind, you need to use <%= isAdmin%> , not <%# isAdmin()%>

I had a similar issue earlier and I solved it by declaring a protected variable in .aspx.cs file and directly using it in the aspx page.
Aspx Page:
<li runat="server" id="li1" visible ='<%# IsAdmin %>'>
<span> Admin link</span>
</li>
Aspx.cs File:
protected bool IsAdmin = false;

in aspx files you can try :
<% if (isAdmin()==true ) { %>
your html codes and server controlls
<%}>
if isAdmin retruns true asp write yours codes in (your html codes and server controlls) your page.

Related

c# asp.net master page get a href and set visible to false

I have an a href link in my user.master page, but I'm unable to find that control in my user.master.cs. How do I do so? I tried using master and find control, but it says object reference is not instance to an object or it does not work. Please help, thanks.
user.master
Upgrade
user.master.cs
(first try)
var masterPage = Master;
if (masterPage != null)
{
masterPage.FindControl("showUpgradeLink").Visible = true;
}
(second try)
this.Master.FindControl("showUpgradeLink").Visible = false;
Did you put runat="server" on the a tag?
For example:
<a href="ViewPremiumPlans.aspx" id="showUpgradeLink" runat="server" class="btn-light btn-sm" >Upgrade</a>
You need to add runat="server" without that it is not a server control.
Upgrade
You then access it in the master (user.master.cs) page directly
showUpgradeLink.visible = false;
If you want to expose it to child pages add a public property to user.master.cs
public HtmlGenericControl UpgradeLink { get { return showUpgradeLink; } };
In your child aspx pages where you want to access the control/property add:
<%# MasterType virtualpath="~/Path/To/user.master" %>
Then in the child .cs pages you can use:
Page.Master.UpgradeLink.visible = false;

asp.net web forms using variables inside a server control

I am trying to use a variable inside server control in asp.net webform page(.aspx). I am getting syntax error. What may be the issue?
<%string msgCancelProject = "You are not authorized to cancel the project."; %>
<asp:Button ID="CancelProject" <%if(IsAuthorized){%> title="<% =msgCancelProject %>" clickDisabled="disable" <%}%> runat="server" Text="Cancel Project" 
                     OnClick="btnCancelProject_Click" 
                    OnClientClick="return confirm('Are you certain you want to cancel the record?');" />
It's not possible to do what you are trying to do with a server control. I.e. adding a property dynamically in markup. You can only set property values but that's not what you want.
You could achieve what you want from the code behind as follows.
Keep your markup like this.
<asp:Button ID="CancelProject" runat="server" Text="Cancel Project" OnClick="btnCancelProject_Click"
OnClientClick="return confirm('Are you certain you want to cancel the record?');" />
And, in your code behind do this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string msgCancelProject = "You are not authorized to cancel the project.";
if (IsAuthorized)
{
CancelProject.Attributes.Add("title", msgCancelProject);
CancelProject.Attributes.Add("clickDisabled", "disable"); // I'm not sure what you are trying to do here
}
else
{
CancelProject.Attributes.Remove("title");
CancelProject.Attributes.Remove("clickDisabled");
}
}
}
Hope this helps.

Is there an ASP.NET databindable control (like Repeater), which only expects a single item?

I'm trying display lots of properties from a business object on a Web Form. I could of course, create loads of labels and assign all the values in code-behind, but I feel there must be a less verbose way.
What I want is something like an asp:Panel but where you can specify a datasource. It doesn't seem like Panels support any kind of databinding.
What I'd like is something like this
// C#
panel.DataSource = theCompany;
panel.DataBind();
Then:
// ASPX
<asp:Panel runat="server">
Name: <%# Eval("Name") %>
Phone: <%# Eval("Phone") %>
...
</asp:Panel>
..but I can't find anything which will allow me to work in this way.
I thought I might be able to use asp:FormView but this just gives the error "Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource."
A caveat is that I do not want to call a global DataBind() (this has caused us no-end of problems in the past) - I would like the databind to be constrained to a particular part of the page.
It seems you can do this using a Panel, but you have to assign your business object to a page property first, as there's no way to set the business object as a "DataSource" for the panel (as you would for a Repeater control, for instance).
Once the object is assigned as a page property, you can then use the following syntax in the .aspx to access the properties of that object, without needing to manually assign each item to control values in code behind:
<%# Company.Name %>
You don't need to databind (although you can). What you need is a simple expression evaluator. Add a property to your code behind like this
public string Test { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Test = "<script>alert('test');</script>";
}
Then use it to render code directly to the page like this
The value: <%: Test %>
Note that the <%: syntax escapes the input. If you wish to NOT escape the input then you can use <%= syntax. Note that you don't need to have a string object you can access any properties you like for example
The value lenght: <%: Test.Length %>
Use The below:
<asp:DetailsView runat="server">
Name: <%# Eval("Name") %>
Phone: <%# Eval("Phone") %>
</asp:DetailsView>
Use DetailsView. You can add it from the Toolbox. It's for Single Row Data Presentation.
<asp:DetailsView runat="server">
Name: <%# Eval("Name") %>
Phone: <%# Eval("Phone") %>
</asp:DetailsView>
Why not using DetailsView. Its perfect for what you want. Showing single row of data only and that too in two column form.
I suggest using a standard Repeater, databound with an array containing a single item.
Repeater.DataSource = new [] { theCompany };
Repeater.DataBind();
Advantage over databinding to a Panel: you can still use the ItemType attribute, and have access to the nice strongly typed Item object and don't have to go about using Eval, i.e.:
<asp:Repeater runat="server" Id="Repeater" ItemType="CompanyViewModel">
<ItemTemplate>
Name: <%# Item.Name %>
Phone: <%# Item.Phone %>
</ItemTemplate>
</asp:Repeater>
(Replace "CompanyViewModel" with the Type of your: "theCompany".)
You can also try experimenting with DetailsView, but it's not as malleable as a Repeater.
Create your own user control that shows the properties of the objects. You can use reflection to read property names and values and display in control.
Create a property for your object in your user control. Inside user control code behind write function Show() with below code.
//Build html strin from all propeties
PropertyInfo[] properties = yourObject.GetType().GetProperties();
string lbl = "<label>{0}</label>";
string value= "<span>{0}</span>";
string tab ="\t";
StringBuilder sb = new StringBuilder();
foreach (PropertyInfo pi in properties)
{
var label = string.Format(lbl,pi.Name);
var val = string.Format(value, pi.GetValue(yourObject, null))
sb.Append(label+tab+val);
sb.Append("<br/>")
}
Response.Write(sb.ToString());
Now in your pager add that control and sets its object property in code behind like
myControl.MyObject = yourObject;
myControl.Show();
NickG's answer will work... however consider two scenarios.
If your business object is ever null, the page will crash with an "Object Reference" error. This can be avoided with a cumbersome looking
<% if(MyObject != null) { %><%= MyObject.Prop %><% } %>
... but doing that every time makes for messy code.
If your page uses PostBack processing via UpdatePanel, the business object will have to be reloaded to the property every time the Page lifecycle runs... even if that portion of the page isn't being redrawn. This is because IIS will resolve all the <%= MyObject.Prop %> references regardless, causing wasted CPU cycles and probably wasted database calls if your object is coming from a database.
For these reasons I always use a Repeater control, which is lightweight, supports ViewState, can easily be assigned a one item list, and avoids the aforementioned issues. Here's an example using the HttpContext.Current.Request object as a "business object".
<asp:Repeater ID="rptTest" runat="server">
<ItemTemplate>
Request.URL = <%# Eval("Url") %>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var objTest = Request; //Using the Request object as a test business object
rptTest.DataSource = new List<System.Web.HttpRequest>() { objTest };
rptTest.DataBind();
}
}
To make this work we can customize ASP.NET Panel by inheriting it and using Custom Server control for ASP.NET
Use Below Code to modify the ASP.NET Panel in an ASP.NET Custom Server Control Project:
[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomPanel runat=server></{0}:CustomPanel>")]
public class CustomPanel : Panel
{
[Bindable(true)]
public object MyDataSource
{
get;
set;
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public StringBuilder Text
{
get;
set;
}
public void MyDataBind()
{
Text = new StringBuilder();
foreach (PropertyInfo p in MyDataSource.GetType().GetProperties())
{
Text.Append(string.Format("<b>{0}</b>", p.Name));
Text.Append(":");
if (p.GetIndexParameters() == null || p.GetIndexParameters().Length == 0)
Text.Append(p.GetValue(MyDataSource, null));
Text.Append("<br />");
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(Text);
}
}
Then add this control's reference and toolbox item to your ASP.NET page:
<cc2:CustomPanel ID="MyCustomPanel" runat="server">
</cc2:CustomPanel>
Use the control as shown below:
MyCustomPanel.MyDataSource = theCompany;
MyCustomPanel.MyDataBind();

Pass a value from aspx to ascx

I have a web page and it contains an user control inside of it. I have a property on the aspx page which gets set in the pageinit method and I need to that propery on ascx page.
How can I get it?
Create a public property inside the ascx and set it at the same time you set in the aspx page.
Just to let you know, PreInit is a EventHandler not a method.
MyAdminPage myPageInstance = this.Parent as MyAdminPage;
if(myPageInstance != null)
{
...
}
There has been a few questions on this.
Reference .aspx property from .ascx
The easiest options are as follows:
Use a public variable and access it from the parent page.
Assign the variable to a hidden field on the ascx front end. A field like this: <asp:HiddenField ID="ascxField" runat="server" /> .
The example below is for #1, but #2 is almost the same.
Example #1:
Aspx page:
Front end:
<%# Register TagPrefix="Admin" TagName="MyUserControl" Src="~/UserControls/.../MyUserControl" %>
...
<Admin:MyUserControl ID="MyUserControl" AutoPostBack="true" runat="server" Visible ="false" />
Code Behind:
this.MyUserControl.Variable1 = 1;
this.MyUserControl.Variable2= "value";
Ascx page:
Code Behind
public int Variable1 { get; set; }
public string Variable2 { get; set; }

Adding an ASP.NET Web User Control to a Control Dynamically

I have a simple ASP.NET Web User Control. It looks like this:
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="NewsArticle.ascx.cs"
Inherits="Website.Controls.NewsArticle" %>
<div>
<asp:Literal ID="ltlBody" runat="server" />
</div>
My code behind looks like this:
namespace Website.Controls
{
public partial class NewsArticle : System.Web.UI.UserControl
{
public String bodyText
{
//get { return ltlBody.Text; }
set { ltlBody.Text = value; }
}
}
}
On a .aspx page I have <asp:Panel ID="pNews" runat="server" />
In the code behind I have:
foreach (vwNews news in newsQuery)
{
NewsArticle article = new NewsArticle();
article.bodyText = news.Body;
pNews.Controls.Add(article);
}
Every time I run this code the newsQuery is populated correctly and I get to the line
aticle.bodyText = news.Body; and then I received the error article.bodyText threw an exception of type 'System.NullReferenceException'
I am not sure what is causing this error message or how to fix it. I would think that there should not be an issue. I tried creating a constructor for my Web User Control so that it would give default values to my properties but that didn't work. Any idea how to make this work? It doesn't seem like it should be that
To load a control programatically you need to use the Page.LoadControl() method. See this MSDN article
You have a typo within the code you've written. 'aticle' instead of 'article'.

Categories