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

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" />

Related

how to display a list of URLs and their title in ASP and c#

i have a list of URLS and titles
i want to show them just like as display in google search results
i have this code
<asp:Repeater id="repLinks" runat="server">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Container.DataItem.ToString() %>' Text="LinkText" />
</ItemTemplate>
</asp:Repeater>
and i have a list
ist<string> lLinks = new List<string>();
lLinks.Add(link.InnerText.Trim());
lLinks.Add(hrefValue.Replace("/url?q=", ""));
repLinks.DataSource = lLinks;
repLinks.DataBind();
i want to change the code to show the titles which is in
link.InnerText.Trim()
for each url not the constant text in Text="LinkText"
any body can help me plz?
Unless I've misunderstood, you want to set the Text property to the same value as the NavigateUrl property. If so, you do the same as you already did...
Text='<%# Container.DataItem.ToString() %>'
If you meant something else, please explain more, as it looks like you're dealing with a plain string, so you've only got the one option.
Edit based on your comment, it looks like you want to use two separate strings in the tag. If so, you'd be better off creating a simple class with two string properties...
public class LinkData {
public string Url { get; set; }
public string DisplayText { get; set; }
}
...and using a collection of these for your data source. You could create the class, and set the two properties in your code behind, then just use the property names in your view code...
Text='<%# Container.DataItem.DisplayText %>'

Calling Static method on aspx page does not work?

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() %>

Reproduce a content of panel dynamically

Is there any way where we can reproduce the content of a panel.For example i have a panel which has two text box .On clicking more button i would like to have another panel below which again has two text box like the first one or add two text box into the existing panel.My end goal is to add controls as the user clicks on more button and get data from those controls .This is the controls inside the panel that i would like to reproduce
any possible way where i can add the controls as shown in the layout through server side ?Please help!
There are plenty ways to solve this. You could add proper DOM elements by yourself using plain JavaScript or jQuery, or use some JS MV* frameworks, like KnockoutJS (example: http://knockoutjs.com/examples/contactsEditor.html) or AngularJS.
you can obviously add dynamic controls from code behind on button click event of 'more button'.
Click Here for more references:
If you want to achieve this on client side using jQuery, then 'closest()' (to find the source element/row to be repeated nearby to the add/remove button etc., especially if it is in a tabular/grid format) in conjunction with 'clone()' function, (to make a copy of the source element/row) and then you can paste the clone inside the target container.
The following link might help you achieve what you want:
jQuery Clone table row
But doing this in Asp.Net WebForms should be much straight forward.
Also, please be noted that, it would always be much helpful to get a quicker answer by specifying more details(eg., MVC, WebForms etc. in the description, what trials you did to find/fix the problem) and that help save other's time as well. For more info: https://stackoverflow.com/questions/how-to-ask
try this
your aspx page add
<asp:TextBox runat="server" ID="TextBox1" />
<asp:TextBox runat="server" ID="TextBox2" />
<asp:Button Text="Add" ID="btnAdd" OnClick="btnAdd_Click" runat="server" />
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:TextBox runat="server" ID="txt1" Text='<%# Eval("str1") %>' />
<asp:TextBox runat="server" ID="txt2" Text='<%# Eval("str2") %>' /><br />
</ItemTemplate>
</asp:Repeater>
and in code behind
protected void btnAdd_Click(object sender, EventArgs e)
{
List<temp> lst = GetItemFromRpt();
lst.Add(new temp
{
str1=TextBox1.Text,
str2 = TextBox2.Text
});
rpt.DataSource = lst;
rpt.DataBind();
}
private List<temp> GetItemFromRpt()
{
List<temp> lst = new List<temp>();
for (int i = 0; i < rpt.Items.Count; i++)
{
temp obj = new temp();
obj.str1 = ((TextBox)rpt.Items[i].FindControl("txt1")).Text;
obj.str2 = ((TextBox)rpt.Items[i].FindControl("txt2")).Text;
lst.Add(obj);
}
return lst;
}
public class temp // instead of temp you can use whatever your entity class you need
{
public string str1 { get; set; }
public string str2 { get; set; }
}

How to create capital letter row for a list of names in an ASP Repeater

I'm using an asp repeater to display a list of names and I want to display the current letter as a type of grouping header, like in an index page.
The data is sorted alphabetically before binding, but i'm finding it difficult to insert the 'A' and 'B' before the names are displayed.
Add a Panel control to your ItemTemplate with visibility set to False. When you are binding the repeater (assuming you are subscribing to the ItemDataBound event), run a check to see if the first letter has changed. If it has, set the panel's visibility to true and print out the letter.
Let me know if you need some example code.
EDIT: EXAMPLE CODE
For clarity sake, "AlphaHeaders" is what we will call the "A", "B", "C" letters that we want to display
aspx code
The Repeater will look like so:
<table>
<asp:Repeater id="rptRepeater" runat="server" OnItemDataBound="rptNames_OnItemDataBound">
<ItemTemplate>
<asp:Panel id="pnlAlphaHeader" runat="server" visible="False">
<tr><td><asp:Label id="lblAlphaHeader" runat="server" /></td></tr>
</asp:Panel>
<tr><td><asp:Label id="lblName" runat="server" /></td></tr>
</ItemTemplate>
</asp:Repeater>
</table>
aspx.cs code
First, you need a variable that holds the current AlphaHeader:
private string _AlphaHeaderCurrent = String.Empty;
Then you will do your work on the repeater's OnItemDataBound event:
protected void rptNames_OnItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if ((e.ItemType==ListItemType.Item) || (e.ItemType==ListItemType.AlternatingItem)) {
string name = e.Item.DataItem("Name").ToString();
//check if the first letter of the current name is new. If it is new, we print out the header
if(!name.StartsWith(this._AlphaHeaderCurrent)) {
this._AlphaHeaderCurrent = name.SubString(1);
((Panel)e.ItemFindControl("pnlAlphaHeader")).Visible = true;
((Label)e.Item.FindControl("lblAlphaHeader")).Text = the._AlphaHeader;
}
((Label)e.Item.FindControl("lblName")).Text = name;
}
}
You sort before you bind.
That is, bind the sorted result set.
Without seeing the values you have, however, it is not possible to tell exactly how to do so.
Update - from your comment, I would say you need to change your binding source to something like Dictionary<string,IList<string>>.
With such a structure, you could bind by key (sorted) and sublist (secondary sort).
You need to sort your data before bind it to the repeater.
You can use nested repeaters (repeater inside repeater). Like category and subcategory.
In first repeater you can list all your names and make a condition starts with A. Then in sub repeater you can show all names. You will also use itemdatabound event to bind second repeater.
<asp:Repeater id="rptFirstLetters" runat="server" OnItemDataBound="rptChars_OnItemDataBound">
<ItemTemplate>
<div>"<%#Eval("letters") %>"
<asp:Repeater id="rptNames" runat="server">
<ItemTemplate>
<%#Eval("names") %>
</ItemTemplate>
</asp:Repeater>
</div> // bind all letters
</ItemTemplate>
Not really a nice way of doing this to be honest, repeaters generally result in ugly code I've found. The hierarchical approach from kad1r is probably the nicest if you can set it up, but there are alternatives, depending on your implementation details; I kind of prefer this in some ways as it keeps the markup very clean, and as I have a non-programmer design guy that is a plus for me.
ASPX:
<%# Page language="C#" Src="test.CODE.cs" Inherits="test_Page" %>
<asp:Repeater ID="TestRepeater" runat="server">
<ItemTemplate>
<asp:PlaceHolder Visible='<%# Eval("IsFirstInGroup") %>' runat="server">
<strong><%# Eval("Initial") %></strong><br/>
</asp:PlaceHolder>
<%# Eval("Name") %><br/>
</ItemTemplate>
</asp:Repeater>
CODE BEHIND:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class test_Page : Page
{
protected Repeater TestRepeater;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
String[] names = new String[]
{
"Alpha, John",
"Altman, Mary",
"Asher, Cyril",
"Bachman, Turner",
"Beta, Rob",
"Bexman, Norah",
"Clark, Freddy"
};
List<_DispItem> l = new List<_DispItem>();
for (int i = 0; i < names.Length; i++)
l.Add(new _DispItem() { Name = names[i], IsFirstInGroup = (i == 0 || names[i - 1][0] != names[i][0]) });
TestRepeater.DataSource = l;
TestRepeater.DataBind();
}
private class _DispItem
{
public String Name { get; set; }
public String Initial { get { return Name.Substring(0, 1); } }
public bool IsFirstInGroup { get; set; }
}
}

Set image width dynamically with Eval in ASP.NET

I have an image in a repeater in ASP.NET. I need to set the width of this image dynamically to a value returned from the database. I get the information from the SQL db, then I bind the repeater to the result set or datasource and I try to specify the width of the image in the repeater as follows:
<asp:Image ID="Image1" runat="server" Width='<%# Eval("ImageSize") %>' ImageUrl="~/Images/ProgressBar.jpg"/>
I get an error stating
Specified cast is not valid.
Could this be caused because of the datatype that is being returned from the db?
Use System.Web.UI.WebControls.Unit.Parse method:
<asp:Image
ID="Image1"
runat="server"
Width='<%# System.Web.UI.WebControls.Unit.Parse(Eval("ImageSize").ToString()) %>'
ImageUrl="~/Images/ProgressBar.jpg"/>
Re-Write in aspx file like this:
Width='<%# ConvertToImageSize(Eval("ImageSize")) %>'
Code-Behind:
protected int ConvertToImageSize(object imageSize)
{
int i = 0;
if (imageSize != null)
{
i = Convert.ToInt32(imageSize);
}
return i;
}
A bit rough but I hope you can do the rest of handling at your end easily.

Categories

Resources