Calling Static method on aspx page does not work? - c#

I have a master page named MasterPage_MyMasterPage on whic i have created a static method as
public static string GetRoleName()
{
string sRoleName="admin";
if (HttpContext.Current.Session["UserName"] != null)
{
sRoleName = HttpContext.Current.Session["UserName"].ToString();
}
return sRoleName;
}
and on aspx page i called it as
<a >Brayan <asp:Label runat="server" Text='<%= MasterPage_MyMasterPage.GetRoleName() %>' ></asp:Label>
but it doesn't worked, it print as ...
Brayan <span><%= MasterPage_MyMasterPage.GetRoleName() ;></span>
Session["UserName"] is bind when login successfull.Please help me.

hey please try this works for me
<a >Brayan <asp:Label runat="server" Text='' ><%= MasterPage_MyMasterPage.GetRoleName()%> </asp:Label>

Inline expressions using the <%= ... %> syntax can be used to render to the page.
But they can't be used to set a server-control property, which is what you're attempting to do (Label.Text property).
Consider using data-binding syntax instead:
... Text = "<%# MasterPage_MyMasterPage.GetRoleName() %>"

Could it be the same as this one?
How do I set an ASP.NET Label text from code behind on page load?

Try this
<%= ((MasterPage_MyMasterPage)Page.Master).GetRoleName() %>
Update:
Make a protected method in your cs file something like this
protected string getRoleName()
{
return ((MasterPage_MyMasterPage)Page.Master).GetRoleName();
}
and in aspx file
<%= getRoleName() %>

Related

Pass variable value from aspx link button to code behind in ASP. NET using C#

Inside a for loop, how to pass the variable to the code-behind from an asp tag and access the variable value
CommandArgument works but shows <# gigs[x].Id%> - not the value.
Aspx
<%for (int x = 0; x < gigs.Count; x++){%>
<asp:LinkButton ID="LinkButton2" CssClass="btn btn-danger mt-3" runat="server"
UseSubmitBehavior="false" CommandArgument="<# gigs[x].Id%>"
OnClick="LinkButton2_Click">Hide Gig <i class="fa fa-eye-slash ml-1"></i>
</asp:LinkButton>
Code behind
protected void LinkButton2_Click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
String Value1 = lnk.CommandArgument;
Response.Write(Value1);
}
Result
<# gigs[x].Id%>
Expected Result
1
Try using <%# gigs[x].Id %> instead and call Page.DataBind() on the Page_Load event.
<%= %> is a shortened response.Write() and is never valid as an attribute, for any server tag.
<%# %> can be used, only if the container is databound (the page in your case).
You're much better off using a Strongly Typed Repeater. You can set the ItemType as your class gigs and have full access to all it's properties. Then you can easily use them in the LinkButton.
Repeater1.DataSource = gigs;
Repeater1.DataBind();
And then in the aspx
<asp:Repeater ID="Repeater1" runat="server" ItemType="MyNameSpace.MyClass.Gig">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" CommandArgument='<%# Item.Id %>' OnClick="LinkButton2_Click" runat="server">Hide Gig</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>

ASP.NET <%# Eval("Statement") %> Removes HTML String in Statement?

I'm trying to dynamically populate a table in my ASP.NET webpage from an Azure Storage Table and one of the features I wanted to include is to change the color of the text depending on the value of the element.
I'm using a DataList object which is calling a GetEntries() method to get a list of all the objects to display.
The text in each cell of the table is dynamically displayed using:
<%# Eval("VariableName") %>
So I tried changing the color of the text by doing something like this for each object in the GetEntries() method:
if (condition)
VariableName = "<font color=\"red\">" + VariableName + "</font>";
else
// ...
When I run my program, the text is still black and when I view source, the <font color="red">Bob</font is only Bob.
Does the HTML get stripped when using Eval?
If so, is there an efficient way to change the text color based on the values?
Thanks!
To render as html you can try this:
<asp:Literal Text='<%# Eval("VariableName") %>' Mode="PassThrough" runat="server" />
This requires that you have html (with color info) in VariableName, which may not be pretty.
Alternative 1:
But it will be better if you can add a public property say VariableColor (and leave VariableName unchanged):
public Color VariableColor
{
get
{
return <condition>? Color.Red : Color.Empty;
}
}
and use it like this:
<asp:Label Text='<%# Eval("VariableName") %>' ForeColor='<%# Eval("VariableColor") %>' runat="Server" />
Alternative 2:
Even better could be to create a public bool property (say IsDangerous) which evaluates the condition:
public bool IsDangerous
{
get
{
return <condition>;
}
}
and use it like this:
<asp:Label Text='<%# Eval("VariableName") %>' ForeColor='<%# ((bool)Eval("IsDangerous"))?Color.Red:Color.Empty %>' runat="Server" />

Bind serverside function with Hyperlink control in asp.net web form page

I have few controls on asp.net web form page and i want to link a code behind function to Hyperlink to resolve URL
HTML & Code Behind Example
<asp:HyperLink ID="hyplnkVideo" runat="server" NavigateUrl='<%# this.getVideoPageURL()%>'>
<div id="dAlbumCategory" class="AlbumCategoryIcon">
<asp:Image ID="Image1" ImageUrl='~/Images/gallery/Videos.png' runat="server" />
</div>
</asp:HyperLink>
protected String getVideoPageURL()
{
string url;
int PageID = Helper.GetPageIDbyName("Videos.aspx", Request["Language"]);
url = "~/en/Videos.aspx?PageID=" + PageID + "&Language=" + Request["Language"];
return url;
}
This Hyperlink control is not inside any grid view or repeater control. I tried several way but for some reason it doesn't call the function.
I would appreciate help in this regard
try in this way...
<% getVideoPageURL(); %>
<asp:HyperLink ID="hyplnkVideo" runat="server">
<div id="dAlbumCategory" class="AlbumCategoryIcon">
<asp:Image ID="Image1" ImageUrl='~/Images/gallery/Videos.png' runat="server" />
</div>
protected void getVideoPageURL()
{
string url;
int PageID = Helper.GetPageIDbyName("Videos.aspx", Request["Language"]);
url = "~/en/Videos.aspx?PageID=" + PageID + "&Language=" + Request["Language"];
hyplnkVideo.Attributes.Add("href", url);
}
This is running code.. so u can try it
Simply try this:
NavigateUrl="<%= getVideoPageURL() %>"
The appropriate tag would be <%=, not <%#, as the <%# and %> tags indicate that you want to run data binding code (as in, something you've returned from the database).
It has been a while since this question was asked and marked as resolved.
However for the sake of providing a more appropriate resolution please call DataBind on your page code-behind in page load or render.This will inject the necessary href string.

ASP/C#, adding text to textbox problem

For some reason, I cannot get text into any textbox or label!
I'm using Master pages and the code is going in the code behind view. I have created the textbox:
<asp:Textbox ID="whatever" runat="Server">
When I want to add some text I simply add the code in the code behind view like:
whatever.Text = "myText";
I get an error that says:
"System.NullReferenceException:Object reference not set to an instance of an object"
hightlighting this line in red: whatever.Text = "myText";
I guess its because it saying it not there but how can it let me reference the textbox?
Apologies if the answer is on the site, I have searched but found nothing. :)
This is my code in Basket.asp - I've changed the textbox to a label, it's called bskItems
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
<asp:Label ID="bskItems" runat="server"></asp:Label>
<div id="cart">
<asp:Button ID="btnCheckout" CssClass="BasketBtnAdd" runat="server" CommandName="checkout" Text="Checkout" />
</div>
</asp:Content>
This is my masterpage, where I'm using a loginView. ContentPlaceHolder3 is where the textbox should be. I only want it to display a count of items.
<asp:LoginView ID="loginView" runat="server">
<LoggedInTemplate>
<asp:LoginName ID="loginName" runat="server" FormatString="Hi, {0}!"/>
(<asp:LoginStatus ID="loginStatus" runat="server" />)
<%
if (HttpContext.Current.User.IsInRole("Admin"))
{
%>
<asp:SiteMapDataSource ID="admin" SiteMapProvider="admin" runat="server" ShowStartingNode="false" />
<asp:Menu ID="Menu" runat="server" DataSourceID="admin">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
<%
}
if (HttpContext.Current.User.IsInRole("Users"))
{
%>
<asp:SiteMapDataSource ID="user" runat="server" SiteMapProvider="user" ShowStartingNode="false" />
<asp:Menu ID="Menu1" runat="server" DataSourceID="user">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
<%
}
%>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server"></asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server"></asp:ContentPlaceHolder>
</LoggedInTemplate>
<AnonymousTemplate>
<asp:LoginStatus ID="loginStatus" runat="server" />
<asp:SiteMapDataSource ID="anon" runat="server" SiteMapProvider="anon" ShowStartingNode="false" />
<asp:Menu ID="Menu2" runat="server" DataSourceID="anon">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
</AnonymousTemplate>
</asp:LoginView>
In addition to the other answers, if you're setting the value in Page.OnLoad, remember that the Master page controls haven't been created yet.
Here's a complete layout of the order in which things happen: Complete Lifecycle of an ASP Page
What I usualy do is to make the control visible as a property of my MasterPage.
On the master page (AMasterPage.master):
public TextBox MyTextBox { get { return this.theTextBoxControl; } }
So then, on a child using this masterPage (APage.aspx) :
((AMasterPage)this.Master).MyTextBox.Text = "myText";
When accessing Master Page members from Code-Behind in a Content Place Holder file, I believe you need to do:
this.Master.whatever.Text = "new Text";
Check this link on ASP.NET Master Pages, from MSDN.
You need to do get a reference to the textbox on the master page, then set the text
TextBox tb = Master.Page.FindControl("whatever") as TextBox;
if(tb != null)
{
tb.Text = "myText";
}
Set the ClientIDMode on the textbox to "Static". When the page is rendered it assigns the TextBox's ID to something random. By changing the ClientIDMode to "Static", you should be able to reference the ID because the ID will stay the same and not change.
Or try adding an OnDataBinding event handler and casting the "sender" as a (TextBox). For example:
protected void TextBox_OnDataBinding(object sender, EventArgs e)
{
var txt = (TextBox)sender;
txt.Text = "Something";
}
This should talk to the control directly.

question about buttons and passing a value

i have in my aspx page
<%
for(int i=0;i<10;i++)
{
LinkButton1.CommandArgument=i.ToString();
%>
<asp:LinkButton ID="LinkButton1" runat="server" OnCommand="LinkButton1_Click"></asp:LinkButton>
<%
}
%>
how can i pass a value in my aspx.cs page like:
protected void LinkButtonStergeArticol_Click(object sender,CommandEventArgs e)
{
String id = e.CommandArgument.ToString();
}
?
i know it's not correct because i have more LinkButtons with the same ID, but is there any solution for my problem in this scenario? Or can you suggest me another approach?
i need to have a linkbutton for every item i have in an array. then i need to pass the item's index so that i can delete it in my aspx.cs page.
Can't you use a Repeater or ListView to generate that list of controls? Those are designed to generate a list of controls.
Have you tried something like following?
<%
for(int i=0;i<10;i++)
{
//LinkButton1.CommandArgument=i.ToString();
%>
<asp:LinkButton ID="LinkButton1"
runat="server"
OnCommand="LinkButton1_Click"
CommandName="SomeCommand"
CommandArgument="<%= i%>"></asp:LinkButton>
<%
}
%>

Categories

Resources