How can i insert a C# list into a Div? - c#

I have a C# list:
List<string> Listtags = GetListTag.GetTagList().ToList();
And, I would like to put it into a Div:
<div id="tags">
<ul>
<li><This should be populated with my list></li>
//This list can have any number of items depending on how big my list tags is
</ul>
</div>
Could someone show me how to do this?

you can also use Repeater
<ul>
<asp:Repeater runat="server" id="R">
<ItemTemplate>
<li><%# Container.DataItem %></li>
</ItemTemplate>
</asp:Repeater>
</ul>
and in runtime
List<string> ListTags = GetListTag.GetTagList().ToList();
R.DataSource = ListTags;
R.DataBind();

Use asp:bulletedList and your list will be much easier.
<div id="tags">
<asp:BulletedList id="blTabs"
BulletStyle="Disc"
DisplayMode="LinkButton"
runat="server">
</asp:BulletedList>
</div>
Code Behind:
ListItem li = new ListItem();
li.Value = "html text"; //html goes here i.e. xtab1.html
li.Text = "New Text"; //text name goes i.e. here tab1
blTabs.Items.Add(li);

If you're using ASP.NET, you could use a BulletedList webserver control:
<asp:BulletedList ID="BulletedList1" runat="server"
BulletStyle="Circle"
DisplayMode="Text">
</asp:BulletedList>
and in codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> Listtags = GetListTag.GetTagList().ToList();
Listtags.ForEach(t => BulletedList1.Items.Add(t));
}
}
Edit: "I want to add something like this::: Listtags.ForEach(t => BulletedList1.Items.Add(t),"$tag$ "); weight being a variable in my code"
So i assume that you want to add hyperlinks and apply a different css class on the items.
<asp:BulletedList ID="BulletedList1" runat="server"
CssClass="TagList"
DisplayMode="HyperLink">
</asp:BulletedList>
and for example the css:
<style>
.TagList a {text-decoration:none}
.TagList a:link {text-decoration:none}
.TagList a:visited {text-decoration: none; color: blue}
.TagList a:hover {text-decoration: underline; color: red}
</style>
and how you add the links dynamically(the value of the ListItem is the URL):
Listtags.ForEach(t =>
BulletedList1.Items.Add(new ListItem(t, browseUrl + "?tag=$urlencodetag$"))
);

If you are using MVC3 you can do something like the following:
<div id="tags">
<ul>
#foreach(var item in Model.Listtags)
{
<li>#item.YourPropertyName</li>
}
</ul>
</div>

In Asp.Net
<ul id = "myul" runat = "server">
</ul>
In Code Behind (In Page Load I suppose or button click)
Listtags.ForEach(x => new ListItem(){Text = x });

Related

Get values of checkbox in repeater

I have a repeater inner another repeater and this second one i have a list of checkbox and i need to get the value of the checked.
This is my front code:
<asp:Repeater runat="server" ID="rptPerfis" OnItemDataBound="ItemBound">
<ItemTemplate>
<div class="mws-form-row">
<ul class="mws-form-list inline" style="float: none; display: inline;">
<li style="padding-top: 10px;">
<%# rptNome(Container) %></li>
</ul>
<asp:Repeater runat="server" ID="rptUsers">
<ItemTemplate>
<div class="mws-form-item radioPermissoes clearfix" style="float: none;">
<ul class="mws-form-list inline">
<li>
<asp:CheckBox runat="server" Text="<%# rptAdministradorNome(Container) %>" ID="checkUser" CssClass="<%# rptAdministradorPostClass(Container) %>" /></li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<br />
<hr />
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton runat="server" ID="fLnkSalvar" class="mws-ic-16 ic-disk" OnClick="fLnkSalvar_Click">Salvar</asp:LinkButton>
and this is how i fill this repeater:
protected void Page_Load(object sender, EventArgs e)
{
listaAdm = Servicos.AdministradorMySql.ListarEmpresa(denuncia.Empresa).OrderByDescending(x => x.Nome).ToList();
todosPerfis = Servicos.Perfil.ListarTodos().ToList();
rptPerfis.DataSource = todosPerfis.Where(x => x.Ativo).OrderBy(x => x.Nome);
rptPerfis.DataBind();
}
protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
{
int idPerfil = ((Perfil)args.Item.DataItem).ID;
Repeater childRepeater = (Repeater)args.Item.FindControl("rptUsers");
childRepeater.DataSource = listaAdm.Where(x => x.Perfil > 1 && x.Perfil == idPerfil).ToList();
childRepeater.DataBind();
}
}
protected void fLnkSalvar_Click(object sender, EventArgs e)
{
Administrador usuario = new Administrador();
usuario.Permissoes = new List<string>();
// i need to get this values here to fill this `List<string>` and then save
foreach (var x in usuario.Permissoes)
{
Servicos.Denuncia.InserirUsuarios(denuncia.ID, x);
}
}
I've no idea how can i get this values or if there another easier way without add in the list i think its better
You have to use FindControl on multiple levels. First the correct Item in the parent Repeater, then find the CheckBox in the correct Item of the child Repeater.
var cb = ((Repeater)rptPerfis.Items[i].FindControl("rptUsers")).Items[j].FindControl("checkUser") as CheckBox;
PS you need to wrap the code in Page_Load in an IsPostBack check or you will never retrieve the correct checkbox state in a PostBack.

how to use ul and li in code behind c#

I am trying to fill li and ul of an HTML file using my database.
single category representing multiple items in database.
I have taken the li items in a string, I am replacing [food] with CATEGORY name and [itemTemplate] with ITEMS. The issue in my code is the category name is repeating
Every time as new item display. I have to show category name once and add all related items within that category.
String liTemplate = "<li><h4 class='menu-title-section'> <h4 class='menu-title-section'><a href='#appetizers'>[food]</a></h4>[itemTemplate]</li>";
String itemTemplate = "SOME ITEM TEMPLETE";
DataTable dt = dm.GetData("spTestMenu")
StringBuilder sb = new StringBuilder();
sb.Append("<ul class='our-menu'>");
String liTemplateWorkingCopy = String.Empty, itemTemplateWorkingCopy = String.Empty
foreach (DataRow level1DataRow in dt.Rows)
{
liTemplateWorkingCopy = liTemplate;
itemTemplateWorkingCopy = itemTemplate;
SubCategoryName = level1DataRow["MealSubCatName"].ToString();
if (!previusSubCat.Equals(SubCategoryName))
{
liTemplateWorkingCopy = liTemplateWorkingCopy.Replace("[food]", level1DataRow["MealSubCatName"].ToString());
previusSubCat = SubCategoryName;
}
itemTemplateWorkingCopy = itemTemplateWorkingCopy.Replace("[foodtitle]", level1DataRow["itemName"].ToString());
itemTemplateWorkingCopy = itemTemplateWorkingCopy.Replace("[imgsrc]", level1DataRow["imageURL"].ToString());
itemTemplateWorkingCopy = itemTemplateWorkingCopy.Replace("[price]", level1DataRow["Price"].ToString());
liTemplateWorkingCopy = liTemplateWorkingCopy.Replace("[itemTemplate]", itemTemplateWorkingCopy);
sb.Append(liTemplateWorkingCopy);
foodMenu.Text = sb.ToString();
}
You can set runat="server" for <li> or <ul>..
<li class="abc" runat="server" id="first"></li>
I would suggest using a ListView control for this. This way you can maintain the HTML outside of your code; it's cleaner that way and much more elegant.
Group your rows by the 'MealSubCatName' column, and use LINQ to create an anonymous object:
C#
var grouped = dt.AsEnumerable().GroupBy(c => c["MealSubCatName"].ToString())
.Select(g => new
{
category = g.FirstOrDefault()["MealSubCatName"].ToString(),
items = g.Select(r => new {
title = r["itemName"].ToString(),
image = r["imageURL"].ToString()
})
});
lvFood.DataSource = grouped;
lvFood.DataBind();
ASPX
<asp:ListView ID="lvFood" runat="server">
<LayoutTemplate>
<ul>
<asp:PlaceHolder runat="server" ID="groupPlaceholder" />
</ul>
</LayoutTemplate>
<GroupTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</GroupTemplate>
<ItemTemplate>
<li>
<h4 class="menu-title-section">
<%# Eval("category") %>
</h4>
</li>
<asp:Repeater ID="rpt" runat="server" DataSource='<%# Eval("items") %>'>
<ItemTemplate>
<img src="<%# Eval("image")%>" alt="<%# Eval("title")%>" />
<strong><%# Eval("title")%></strong><br />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:ListView>
Add a div with runat server and assign a Id to that div and do something like this I did this trick here www.journeycook.com Check menu of this website.
Suppose you have a div with id link and runat server in ul tag
<ul>
<div runat="server" id="link">
</div>
</ul>
Now add c# code for fetch data using SqlDataReader class and using while loop do something like this
link.innerhtml+="<li>dr["yourcolumn"].ToString()</li>";
I hope it will give you some help

Making active hyperlink bold and underline asp.net

I am working on an asp.net page. I have two hyperlinks and I want to make them active ( apply a style sheet, make bolder and underline) but somehow it is not doing it.
Here is html:
<li style="margin-left: 10px">
<asp:Literal ID="ltrlRegiosn" runat="server" Text="<%$ Resources: HRGELoggedOutMaster, Language %>"></asp:Literal>:
</li>
<li class="active1"> <asp:HyperLink ID="Lang1HyperLink" runat="server" /></li>
<li><asp:HyperLink ID="Lang2HyperLink" runat="server" /></li>
and style sheet is:
<style>
.active1{
font-weight: bold;
}
</style>
and here is how i am trying to do it using code behind:
if (Page.CurrentLanguage == 1)
{
Lang2HyperLink.CssClass = "active1";
Lang2HyperLink.Font.Bold = true;
Lang2HyperLink.Font.Underline = true;
}
else
{
Lang1HyperLink.CssClass = "active1";
Lang1HyperLink.Font.Bold = true;
Lang1HyperLink.Font.Underline = true;
}
With this code, it becomes underlined but not bold.
Here is output html:
<li class="active1"> <a id="ctl00_ctl00_languageSwitcher_Lang1HyperLink" href="/AllVacancies.aspx?lang=2">Рус</a></li>
<li class="active1"><a id="ctl00_ctl00_languageSwitcher_Lang2HyperLink" class="active1" href="/AllVacancies.aspx?lang=1" style="font-weight:bold;text-decoration:underline;">Eng</a></li>
Please suggest how to fix it ?
There's no need to set the style properties using code behind. when you are already setting the CssClass. Just modify your CSS:
.active1
{
font-weight: bold;
text-decoration:underline;
}
And then you can set just the CssClass via code behind:
if (Page.CurrentLanguage == 1)
{
Lang2HyperLink.CssClass = "active1";
}
else
{
Lang1HyperLink.CssClass = "active1";
}
One more thing: I noticed that you have set the "Active1" class on your <li> as well:
<li class="active1">
That seems like it might be a typo, or at the very least will be confusing for you. I would remove that.

How to retrieve details from a repeater control to display in modal popup

I have a repeater control which displays an image and some basic information like DateTime and Prouct Id. On clicking an Image I need to run another query and show details in a seperate popup.I know how to do the popup.
I want to know how I can fetch the DateTime and ProductId from the repeater and use them in the button click event of the image?
I have my code for the repeater below :
<asp:Repeater ID="rptMonitorSummary" runat="server" OnItemDataBound="rptMonitorSummary_OnItemDataBound">
<ItemTemplate>
<asp:Panel ID="Pnl" runat="server">
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">
<%# Eval("Name").ToString().Length > 9 ? (Eval("Name") as string).Substring(0, 9) : Eval("Name")%>
</h5>
<div id="divHover">
<asp:ImageButton Width="80px" ID="btnPerformanceImage" onclick="btnPerformanceImage_Click" runat="server" Height="45px">
</asp:ImageButton>
</div>
<div class="tooltip" style="display: none">
<div style="text-align: center; font-weight: bold;">
<%# Eval("DateTime") %><br />
</div>
<div style="text-align: center; font-weight: normal">
ErrorRatingCalls =
<%# Eval("ProductId")%><br />
</div>
<div style="text-align: center; font-weight: normal">
TotalRatingCalls =
<%# Eval("TotalCalls")%>
<br />
</div>
<div style="text-align: center; font-weight: normal">
SuccessRate =
<%# Eval("PassPercentage") + "%" %>
</div>
</div>
</li>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
I also have the button click event below :
protected void btnPerformanceImage_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript
(this, this.GetType(), "callScriptFunction", "ViewModelPopup1();", true);
}
All I want to know is how I can fetch the values that are already bound to the repeater control, When I click on an image which inside the repeater control
Instead of handling click on the button itself, you should rather make use of ItemCommand event of the Repeater control. As a CommandArgument you can pass ProductId, and then inside the handler use it to retrieve rest of the info from the DB. Or you can even include all needed values into CommandArgument as a single string and do some parsing afterwards:
<asp:Repeater ... OnItemCommand="rptMonitorSummary_ItemCommand" ... >
...
<asp:ImageButton ... CommandName="ShowPopup" CommandArgument='<%# Eval("ProductId") + "," + Eval("DateTime") %>'>
</asp:ImageButton>
...
</asp:Repeater>
The handler might look like this:
protected void rptMonitorSummary_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
string[] tokens = e.CommandArgument.ToString().Split(',');
int productId = int.Parse(tokens[0]);
DateTime dateTime = Date.Time.Parse(tokens[1]);
// the rest of the handling here
}
Use the OnItemCommand event to fetch values out of the repeater control.
<asp:Repeater ID="rptMonitorSummary" runat="server" OnItemDataBound="rptMonitorSummary_OnItemDataBound" OnItemCommand="rptMonitorSummary_ItemCommand">
.
.
.
<asp:ImageButton Width="80px" ID="btnPerformanceImage" CommandName="Popup" runat="server" Height="45px"></asp:ImageButton>
.
.
.
protected void rptMonitorSummary_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Popup")
{
DataRowView row = ((DataRowView)e.Item.DataItem).Row;
string data1 = Convert.ToString(row["Data1"]);
string data2 = Convert.ToString(row["Data2"]);
ScriptManager.RegisterStartupScript
(this, this.GetType(), string.Format("callScriptFunction", "ViewModelPopup1('{0}','{1}');", data1, data2), true);
}
}
Rather than the OnClick inside your Button, use the OnItemCommand="rptMonitorSummary_ItemCommand" in your Repeater
Then on the code behind
protected void rptMonitorSummary_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
// e.CommandName and e.CommandArgument will let you know what was clicked
}
Your button can look something like this
<asp:Button runat="server" ID="btnPerformanceImage" Text="Whatever" CommandName="OpenImage" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ProductId") %>' />
So then you know what the user clicked on and can change the popup to suit it
you can set a class attribute name for both div tags wich contains the date value and ProductId value and next get them with jquery .find('classname') to retreive their values.

Select All Items in asp.net CheckBoxList

ASP.NET and C#.
I'd like to have a CheckboxList with a "Select All" item.
When this particular item is
selected, all others will be selected
too.
When selection is removed from
this item, so too will it be from all
others items.
Checking/Unchecking of
any other items will only have an
effect on that particular item
regardless of the selection state of
"Select All" item.
I am looking for a jquery solution to this.
Here is the databinding code in my codebehind:
IList<Central> Centrals = new CentralProvider().GetAllCentralsAsList();
Centrals.Insert(0, new Central(){Central_ID = 999, Central_Name = "Select All"});
CentralChecks.DataSource = Centrals;
CentralChecks.DataTextField = "Central_Name";
CentralChecks.DataValueField = "Central_ID";
CentralChecks.DataBind();
And here is the markup:
<div class="CentralDiv" id="CentralDiv">
<h2>Centrals:</h2>
<span>
<asp:TextBox ID="CentralTextBox" runat="server" CssClass="textbox">Centrals</asp:TextBox>
<img id="CentralArrow" src="images/down_arrow.jpg" style="margin-left: -22px; margin-bottom: -5px" />
</span>
<div id="CentralEffect" class="ui-widget-content">
<asp:CheckBoxList ID="CentralChecks" runat="server" onclick="GetSelectedCentralValue();">
</asp:CheckBoxList>
</div>
</div>
Note that there are multiple checkbox lists on the page, so any solution must keep this in mind.
Something like you could use for any of your checkbox lists, just add a cssclass of myCheckBoxList to each CheckBoxList control:
$('.myCheckBoxList :checkbox').eq(0).click(function() {
var toggle = this.checked;
$('.myCheckBoxList :checkbox').attr("checked", toggle);
});
You can iterate through all ListItems on click of Select All. And maintain a state flag to maintain whether all checkboxes are checked or not
if(boolAllChecked) {
foreach (ListItem listItem in CentralChecks.Items)
{
listItem .Selected = false;
}
}
else {
foreach (ListItem listItem in CentralChecks.Items)
{
listItem .Selected = true;
}
}
here is an example: http://jsfiddle.net/VTgGA/
code:
$('input:checkbox').click(function(){
var $this = $(this);
if($this.attr('ref') != 'checkall'){
$(".select-all").attr('checked',false);
}
else {
//Select All
var $checked = $this.is(':checked');
$('input:checkbox').each(function(){
$(this).attr('checked',$checked);
})
$(".select-all").attr('checked',$checked);
}
})
this is what the html of the checkboxes:
<input type='checkbox' ref='checkall' class='select-all'/>
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
Extending mdmullinax's brilliant answer, I came up with this generic solution for "select all" behavior that also unticks the "select all" (i.e. first) option if any other option is unticked and reticks the "select all" when all other items are ticked.
It also executes on window load as I inject it from ASP.Net server-side controls (which inject script in the head section of the page). Better to be safe than sorry :)
$(window).load(function () {
var cbs = $('.myCheckBoxList :checkbox');
cbs.eq(0).click(function () {
var toggle = this.checked;
cbs.attr('checked', toggle);
});
cbs.slice(1).click(function () {
if (!this.checked) {
cbs.eq(0).attr('checked', false);
} else {
cbs.eq(0).attr('checked', cbs.slice(1).filter(':not(:checked)').length == 0);
}
});
});
There is a generic way of having a select all item in asp CheckBoxList with using jquery.
You can have as many as CheckBoxList controls on the form with the select all functionality.
you only need to make sure
Your CheckBoxList has allowSelectAll Class
You added a ListItem to your checkbox list to allow users to select
All with the value of All
chkBoxList.Items.Insert(0, new ListItem("All", "All"));
you Only need the following code
<script>
$('.allowSelectAll :checkbox[value=All]').click(function () {
var toggle = this.checked;
$(this).closest('.allowSelectAll').find(":checkbox").attr("checked", toggle);
});
</script>
In the following code spinet I have 4 Checkbox lists
<div >
<label>Experience 1</label>
<asp:CheckBoxList ID="chklstExp1" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Experience 2</label>
<asp:CheckBoxList ID="chklstExp2" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Experience 3</label>
<asp:CheckBoxList ID="chklstExp3" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<label>Location</label>
<asp:CheckBoxList ID="chklstLocation" runat="server" CssClass="allowSelectAll">
</asp:CheckBoxList>
<asp:Button runat="server" ID="btnShowReport" OnClick="btnShowReport_Click" Text="Show Report"/>
</div>

Categories