javascript menu items database driven - c#

I'm using a javascript menu from dynamicdrive
I'd tried to get the menu items from a database.
my aspx file contain the menu and it works fine when it's a static menu.
my table or my query actually produces:
IdPage int, PageTitle varchar(20), PageFileUrl varchar(30), ParentIdPage int
My methods to get data
DataRow[] dataRowParent = _dataTable.Select("[ParentIdPage]=" + 0);
foreach (DataRow dr in dataRowParent)
{
HtmlGenericControl li = new HtmlGenericControl("li");
// add <a>
HtmlGenericControl hlink = new HtmlGenericControl("a");
if (dr["PageFileUrl"].ToString() == "") // this item has a submenu.
{
li.Attributes.Add("rel", "ddsubmenu" + dr["IdPage"].ToString());
hlink.Attributes.Add("href", "#");// link should be # when no direct link
hlink.InnerText = dr["PageTitle"].ToString();
li.Controls.Add(hlink);
ulTopMenu.Controls.Add(li);
AddNewUl((int)dr["IdPage"]);
AddSubmenuItems(_dataTable, (int)dr["IdPage"]);
}
else // Direct link ,no submenu
{
hlink.Attributes.Add("href", dr["PageFileUrl"].ToString());
hlink.InnerText = dr["PageTitle"].ToString();
li.Controls.Add(hlink);
ulTopMenu.Controls.Add(li);
}
}
}
private void AddSubmenuItems(DataTable dataTable, int menuId)
{
// create related sub menu
DataView dataView = new DataView(dataTable);
dataView.RowFilter = "ParentIdPage=" + menuId;
foreach (DataRowView subMenuItem in dataView)
{
// find related <ul>
HtmlControl ulControl = (HtmlControl)FindControl("ddsubmenu" + menuId);
// Add new <li><a href="PageFileUrl.aspx" >page title</a> </li>
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlGenericControl hlink = new HtmlGenericControl("a");
hlink.Attributes.Add("href", subMenuItem["PageFileUrl"].ToString());
hlink.InnerText = subMenuItem["PageTitle"].ToString();
li.Controls.Add(hlink);
li.InnerText = subMenuItem["PageTitle"].ToString();
li.Attributes.Add("href", subMenuItem["PageFileUrl"].ToString());
ulControl.Controls.Add(li);
}
}
private void AddNewUl(int menuId)
{
// Add new <ul id="ddsubmenu00" class= "ddsubmenustyle">
HtmlGenericControl newUl = new HtmlGenericControl("ul");
// Set the attributes of the new ul.
newUl.ID = "ddsubmenu" + menuId;
newUl.Attributes.Add("class", "ddsubmenustyle");
placeHolder1.Controls.Add(newUl);
}
My problem is that submenu doesn't appear!, what is wrong?
any help appreciated.

Thanks for all, finally I figured it out:
Replace this line
li.Attributes.Add("rel",""+ "ddsubmenu" + dr["IdPage"].ToString()+"");
with this one:
hlink.Attributes.Add("rel",""+ "ddsubmenu" + dr["IdPage"].ToString()+"");
Now it works properly :-)

Related

how can I find the html element with C#

I have this line in my .aspx code:
<div id="view" class="g2" runat="server">
</div>
but when I want to find this element in C#(aspx.cs) and send data for it, C# cant find it this way:
view.Controls.Add(item);
*item is a html element that I made through this code:
for(int i=0; i<foods.Count; i++)
{
HtmlGenericControl item = new HtmlGenericControl("div");
item.Attributes["class"] = "items";
item.Style["border_bottom"] = "3px solid aqua";
HtmlImage img = new HtmlImage();
img.Src = foods[i].picGet();
HtmlGenericControl mask = new HtmlGenericControl("div");
item.Attributes["class"] = "mask";
HtmlGenericControl h2 = new HtmlGenericControl("h2");
item.InnerHtml = foods[i].fnameGet();
HtmlGenericControl price = new HtmlGenericControl("span");
item.Attributes["class"] = "price";
item.InnerHtml = foods[i].priceGet().ToString() + "ریال";
HtmlGenericControl desc = new HtmlGenericControl("p");
item.InnerHtml = foods[i].describeGet();
mask.Controls.Add(h2);
mask.Controls.Add(price);
mask.Controls.Add(desc);
item.Controls.Add(img);
item.Controls.Add(mask);
view.Control.Add(item);
}
I have written the namespace System.Web.UI.HtmlControls
I saw a course that did the same thing and was successful
the error is that even my visual studio cant find the view that i used in the last line of the for loop.
You can use Control.FindControl to search control with the specified id parameter as follow:
Control view = FindControl("view");
//Then add your item to div
view.Controls.Add(item);

How to get value of selected checkboxlist items using javascript in asp.net

I am working on an asp.net project in which i have a checkboxlist which i have bound using
DataTable dt = new Process_Hotels().SelectAllFacilty();
if (dt.Rows.Count > 0)
{
cblHotelFacility.DataSource = dt;
cblHotelFacility.DataTextField = "Facility";
cblHotelFacility.DataValueField = "ID";
cblHotelFacility.DataBind();
foreach (ListItem li in cblHotelFacility.Items)
{
li.Attributes.Add("JSvalue", li.Value);
}
}
and now i want to get selected value ID of checkboxlist using javascript on button click.For that i have following javascript code on button click:
<script type="text/javascript">
function test() {
var checkList1 = document.getElementById('<%= cblHotelFacility.ClientID %>');
var checkBoxList1 = checkList1.getElementsByTagName("input");
var checkBoxSelectedItems1 = new Array();
for (var i = 0; i < checkBoxList1.length; i++) {
if (checkBoxList1[i].checked) {
checkBoxSelectedItems1.push(checkBoxList1[i].value);
//alert('checked:' + checkBoxSelectedItems1.push(checkBoxList1[i].getAttribute("JSvalue")).value);
alert('checked - : ' + checkBoxList1[i].value)
}
}
}
</script>
but the on clicking button the selected checkboxlist is showing 0. I want to get ID of selected checkboxlist items.Please help.
Try this :
<script type = "text/javascript">
function GetCheckBoxListValues(chkBoxID)
{
var chkBox = document.getElementById('<%= cblHotelFacility.ClientID %>');
var options = chkBox.getElementsByTagName('input');
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < options.length; i++)
{
if(options[i].checked)
{
alert(listOfSpans[i].attributes["JSvalue"].value);
}
}
}
</script>
Try debugging
for (var i = 0; i < checkBoxList1.length; i++) {
console.log(checkBoxList1[i])
if (checkBoxList1[i].checked) {
checkBoxSelectedItems1.push(checkBoxList1[i].value);
//alert('checked:' + checkBoxSelectedItems1.push(checkBoxList1[i].getAttribute("JSvalue")).value);
alert('checked - : ' + checkBoxList1[i].value)
}
}
Check to see id console.log() gives you any information about the object by pressing F12 on console window. Install firebug plugin for Firefox.
May this code help you:
function CheckBoxCheckOrNot(jobskill) {
var c = document.getElementById(jobskill).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
if (c[i].checked) {
alert('checkbox checked');
}
else {
alert('checkbox unchecked');
}
}
}
}
note: jobskill is a container id which contain all check boxes.

How to set treeview's childnode postback false on ASP.NET?

I have a treeview and i want no postback on click any childnodes.And i will get selected childnode value.
I found a solution , when i set "node_.SelectAction = TreeNodeSelectAction.None;" i cant select any childnodes and no highlight on it.
Waiting your helps.Sorry about my en.
Aspx:
<asp:TreeView ID="TreeView1" runat="server"></asp:TreeView>
Cs:
TreeView1.Nodes.Clear();
TreeView1.TreeNodeExpanded += new TreeNodeEventHandler(TreeView1_TreeNodeExpanded);
DataTable dt = ImzaDll.Imza.KategorileriGetir(true);
foreach (DataRow row in dt.Rows)
{
TreeNode node_ = new TreeNode();
node_.Text = row["ACIKLAMA"].ToString();
node_.Value = row["KATEGORI"].ToString();
TreeView1.Nodes.Add(node_);
}
void TreeView1_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
{
addChildNodes(e.Node);
}
private void addChildNodes(TreeNode node)
{
DataTable dt = ImzaDll.Imza.KutuphaneBasliklariGetir(true, node.Value.ToString());
foreach (DataRow row in dt.Rows)
{
TreeNode childNode = new TreeNode();
childNode.Text = row["BASLIK"].ToString();
childNode.Value = row["KUTUPHANE_ID"].ToString();
childNode.ToolTip = row["BASLIK"].ToString() + " kütüphanesini ekle";
childNode.Target = "_new";
node.ChildNodes.Add(childNode);
}
}
You can set CSSClass of treeview child nodes
like
<asp:TreeView LeafNodeStyle-CssClass="childnode" runat="server">....</asp:TreeView>
then using jquery you get get class and set return false like follow.
$(".childnode").click(function(){
return false;
})
...same way you can set RootNodeStyle-CssClass, ParentNodeStyle-CssClass class and use jquery to set them...
TreeNode tn = new TreeNode();
tn.SelectAction = TreeNodeSelectAction.None; OR tn.SelectAction = TreeNodeSelectAction.Expand;
Both of these will not cause postback.
you could remove the href of link('a') tag attribute to stop post back
$('#ctl00_ContentPlaceHolder1_tvHierarchyView table tr td>a').click(function () {
var treeViewData = window["<%=tvHierarchyView.ClientID%>" + "_Data"];
if (treeViewData.selectedNodeID.value != "") {
var selectedNode=document.getElementById(treeViewData.selectedNodeID.value);
var value = selectedNode.href.substring(selectedNode.href.indexOf(",") + 3, selectedNode.href.length - 2);
var text = selectedNode.innerHTML;
alert("Text: " + text + "\r\n" + "Value: " + value);
} else {
alert("No node selected.")
}
$(this).removeAttr("href");
/// ...................... rest of your code
}); /// End of click function
}); /// End of document ready function
Here steps explanation:
Get the dev id which contains the tree table by Using inspect element:
Get details from the selected child node.
After taken the details of child node , remove the attribute "href" to avoid post back.
Do whatever functionality you what do with selected node details (eg pass selected value using ajax)

c#.net how to get a HtmlGenricControll to show a RadioButtonList item

I have a HtmlGenericController and to this I want to add RadioButtons. My radiobuttons come from a RadioButtonList an hence the objects are Listitems. How do I get my genericcontroller to show the radiobuttons?
This is my code
private HtmlGenericControl generateCells(String domainName)
{
HtmlGenericControl container = new HtmlGenericControl("div");
HtmlGenericControl dName = new HtmlGenericControl("span");
dName.InnerHtml = domainName;
RadioButtonList radioList = new RadioButtonList();
radioList.ID = "radio_" + domainName;
radioList.RepeatDirection = RepeatDirection.Horizontal;
ListItem sunriseA = new ListItem();
sunriseA.Value = Price_Types.SUNRISE_ONE.ToString();
//sunriseA.Text = Price_Types.SUNRISE_ONE.ToString();
sunriseA.Text = "";
radioList.Items.Add(sunriseA);
ListItem sunriseB = new ListItem();
sunriseB.Value = Price_Types.SUNRISE_TWO.ToString();
//sunriseB.Text = Price_Types.SUNRISE_TWO.ToString();
sunriseB.Text = "";
radioList.Items.Add(sunriseB);
ListItem landrush = new ListItem();
landrush.Value = Price_Types.LANDRUSH.ToString();
//landrush.Text = Price_Types.LANDRUSH.ToString();
landrush.Text = "";
radioList.Items.Add(landrush);
ListItem general = new ListItem();
general.Value = Price_Types.GENERAL.ToString();
//general.Text = Price_Types.GENERAL.ToString();
general.Text = "";
radioList.Items.Add(general);
container.Controls.Add(dName);
foreach (ListItem item in radioList.Items)
{
HtmlGenericControl span = new HtmlGenericControl("span");
span.InnerHtml = item;//what to put here??
container.Controls.Add(span);
}
return container;
}
var radioButton = new HtmlGenericControl("input");
radioButton.Attributes["type"] = "radio";
radioButton.Attributes["name"] = "groupName";
radioButton.Attributes["value"] = "buttonValue";
That will only render the round radiobutton itself, though. To add a label, you'll have to render for example a span besides it. Or, IIRC, render a label field with the for attribute set to the ID of the radiobutton, so clicking the label will automatically click the button too.

Creating an ASP.NET Repeater Dynamically in C# Bound to an Object List

I've got a very simple object:
public class DocumentType
{
private int id;
private string name;
public int ID
{
get { return this.id; }
set { this.id = value; }
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
}
I've got a list of DocumentType objects: List<DocumentType> documentTypes = getDocuments();
I'm working on a custom control where I'm trying to dynamically create a repeater and dynamically bind it to my object list. Here's my code:
private Repeater docList;
docList = new Repeater();
docList.DataSource = documentTypes;
docList.DataBind();
foreach (RepeaterItem repeatItem in docList.Items)
{
// if condition to add HeaderTemplate Dynamically only Once
if (repeatItem.ItemIndex == 0)
{
RepeaterItem headerItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Header);
HtmlGenericControl hTag = new HtmlGenericControl("h4");
hTag.InnerHtml = "Header";
repeatItem.Controls.Add(hTag);
}
// Add ItemTemplate DataItems Dynamically
RepeaterItem repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Item);
Label lbl = new Label();
// This part is completely broken!
lbl.Text = string.Format("Content: {0} {1} <br />", (DocumentType)repeaterItem.DataItem).ID, repeaterItem.NamingContainer);
repeatItem.Controls.Add(lbl);
// Add SeparatorTemplate Dynamically
repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Separator);
LiteralControl ltrlHR = new LiteralControl();
ltrlHR.Text = "<hr />";
repeatItem.Controls.Add(ltrlHR);
}
The header and separator work great. I can't figure out how to bind the item template to the current item to get it to display. I know what I have in there right now is completely broken, but I've tried several variations with no luck.
Thanks in advance for any help or pointers in the right direction!
The problem you are having is that you are assuming that the RepeaterItem contains the data. It does not. It contains the information on how to display the individual item. You need to use that index to get back into the data source. I'm not sure if there's a better way, but below is how I got it to work...
List<DocumentType> documentTypes = new List<DocumentType>();
documentTypes.Add(new DocumentType(){ ID=1, Name="Bob"});
documentTypes.Add(new DocumentType() { ID = 2, Name = "Tom" });
documentTypes.Add(new DocumentType() { ID = 3, Name = "Chick" });
Repeater docList = new Repeater();
docList.DataSource = documentTypes;
docList.DataBind();
foreach (RepeaterItem repeatItem in docList.Items)
{
int index = repeatItem.ItemIndex;
DocumentType docType = ((IList<DocumentType>)docList.DataSource)[index];
// if condition to add HeaderTemplate Dynamically only Once
if (index == 0)
{
HtmlGenericControl hTag = new HtmlGenericControl("h4");
hTag.InnerHtml = "Header";
repeatItem.Controls.Add(hTag);
}
// Add ItemTemplate DataItems Dynamically
RepeaterItem repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Item);
Label lbl = new Label();
// This part is completely broken!
lbl.Text = string.Format("Content: {0} {1} <br />", docType.ID, repeaterItem.NamingContainer);
repeatItem.Controls.Add(lbl);
// Add SeparatorTemplate Dynamically
LiteralControl ltrlHR = new LiteralControl();
ltrlHR.Text = "<hr />";
repeatItem.Controls.Add(ltrlHR);
}
StringBuilder sb = new StringBuilder();
docList.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
Text = sb.ToString();

Categories

Resources