Inserting items into bootstrap-dropdown from SQL Table - c#

I am working on asp.net project and my code behind language is c#. I have one bootstrap dropdown in which i want to get the items from SQL Table. is there anyone who will help me in this regard. thanks in advance.
<li class="nav-item dropdown">
<a class="btn btn-light dropdown-toggle" href="#" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Category
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
Action, Another Action and Something else items should come from database (Category) Table. Using c# language on server side is much appreciable.

There are some ways to do it in WebForms, but first you need to make the DIV element of the dropdown menu accessible from the Code Behind.
See this snippet?
<ul class="nav nav-tabs">
<li class="nav-item dropdown">
<a class="btn btn-light dropdown-toggle" href="#" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Category
</a>
<div id="myDropdownMenu" runat="server" class="dropdown-menu" aria-labelledby="navbarDropdown">
</div>
</li>
</ul>
Note that I added 2 attributes : id="myDropdownMenu" and runat="server".
After this you can go to Code Behind to start populating the menu from a data source.
At least there are 2 ways to do this, as far as I know.
By manipulating the InnerHtml property, like this :
private void DisplayMenuByConstructingHtmlTags(List<string> menuList)
{
var menuHtml = "";
foreach (string menuText in menuList)
{
menuHtml += "<a class=\"dropdown-item\" href=\"#\">" + menuText + "</a>\n";
}
myDropdownMenu.InnerHtml = menuHtml;
}
Or, by adding the menu as the child controls, like this :
private void DisplayMenuByAddingChildControls(List<string> menuList)
{
foreach (string menuText in menuList)
{
var linkMenu = new HyperLink() { CssClass = "dropdown-item", NavigateUrl = "#", Text = menuText };
myDropdownMenu.Controls.Add(linkMenu);
}
}
It's your call, which one to choose.
Btw, just to complete this example, you may try to call one of those methods from the Page_Load event, like this :
EDIT :
By your request, I've modified the samples by adding a connection to a table in a database. So, this is the module to load the data :
private List<string> LoadMenuFromTable()
{
string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ToString();
var retVal = new List<string>();
using (var connection = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand("SELECT menu_text FROM Table_1", connection))
{
connection.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
retVal.Add((string)reader["menu_text"]);
}
}
}
}
return retVal;
}
And here's how you should call the module :
protected void Page_Load(object sender, EventArgs e)
{
var menu = LoadMenuFromTable();
DisplayMenuByAddingChildControls(menu);
// or DisplayMenuByConstructingHtmlTags(menu);
}
Oh, and remember to import these two libraries to make this sample works :
using System.Configuration;
using System.Data.SqlClient;
Hope it helps.

Related

ASP.NET Hide/disable entire dropdown menu based on user role

I have a drop-down list in an ASP.NET webform application generated in the sitemaster menu using the follow ing code:
<li class="dropdown" id="Admin" > <a class="dropdown-toggle" data-toggle="dropdown" href="#">Admin<span class="caret" ></span></a>
<ul class="dropdown-menu" >
<li><a runat="server" href="~/Admin/Members">Members Management</a></li>
<li ><a runat="server" href="~/Admin/MembersRegistry">Members Registry</a></li>
</ul>
</li>
and the script to generate the drop down is
<script>
$(document).ready(function () {
$(".dropdown").hover(function () {
//toggle the open class (on/off)
$(this).toggleClass("open");
});
})
</script>
I want to be able to hide or show the entire dropdown menu based on user roles:
protected void Page_Load(object sender, EventArgs e)
{
Admin.Visible = false;
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
var user = HttpContext.Current.User.Identity.GetUserId();
if (manager.IsInRole(user, "Admin"))
{
Admin.Visible = true;
}
}
}
But this is not working and the Admin control is not accessible from the code behind, any thoughts or suggestions please?
If you add a runat="server" tag to that, then your code behind should see/have use of that controls, and you code looks like it should work ok.
eg:
<li class="dropdown" id="Admin" runat="server">
.etc. etc.
</li>

How to dynamically add CSS to a menu on click in C#

I would like to dynamically add styling to my menu without using 15 different if-else statements. Perhaps a for loop?
`
C#
String activepage = HttpContext.Current.Request.Url.AbsolutePath;
if (activepage.Contains("Cops"))
{
activateCOPS.Attributes.Add("class", "nav-link active");
}
else if (activepage.Contains("Opac"))
{
activateOPAC.Attributes.Add("class", "nav-link active");
}
else if (activepage.Contains("Etp-Tps"))
{
activateETP_TPS.Attributes.Add("class", "nav-link active");
}
else if (activepage.Contains("Eta"))
{
activateETA.Attributes.Add("class", "nav-link active");
}... etc.
HTML:
<li class="nav-item">
<a id="activateCOPS" class="nav-link" runat="server" href="Cops.aspx">COPS</a>
</li>
<li class="nav-item">
<a id="activateOPAC" class="nav-link" runat="server" href="Opac.aspx">OPAC</a>
</li>
`
Thanks in advance!
You could do the following:
var themes = new Dictionary<string, Func<string[], bool>
{
{"Employee", SetEmployeeSiteTheme },
{"Government", SetGovermentSiteTheme}
}
if(themes.ContainsKey("Employee"))
themes[key].Invoke("Some markup?");
Then inside those methods you can find your control, you can modify the markup, you are not generating a thousand if statements and you can expand the functionality later on depending on your needs.
This would be a better structure to control multiple layouts in my mind, this is how I might tackle your problem. Obviously I did not create a viable solution, I only demonstrated an approach to be a viable solution.

Selenium C# List

Hello Stackoverflow Users,
I have a internet site with 99 list elements.
The diffrence between the elements are only the names.
<li class="_6e4x5">
<div class="_npuc5">
<div class="_f5wpw">
<div class="_eryrc">
<div class="_2nunc">
<a class="_2g7d5 notranslate _o5iw8" title="Name1" href="/"Name1/">"Name1</a>
</div>
</div>
</div>
</div>
</li>
[...]
<li class="_6e4x5">
<div class="_npuc5">
<div class="_f5wpw">
<div class="_eryrc">
<div class="_2nunc">
<a class="_2g7d5 notranslate _o5iw8" title="Name99" href="/"Name99/">"Name99</a>
</div>
</div>
</div>
</div>
</li>
What I want:
I want to take the "title" of each list element and put it in a new list.
What I tried:
List<string> following = new List<string>();
By name = By.XPath("//div[#class='_2nunc']");
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
IList<IWebElement> displayedOptions = driver.FindElements(name);
foreach (IWebElement option in displayedOptions)
{
string temp = displayedOptions[i].ToString();
following.Add(temp);
i++;
}
If I run the code, I only get the element ID, and not the "title" (name34 for example). I hope you have enough information to help me with my problem. Thanks in advance for every help!
To take the title of each list element and put it in a new list you can use the following code block :
List<string> following = new List<string>();
IList<IWebElement> displayedOptions = driver.FindElements(By.XPath("//li[#class='_6e4x5']//a[#class='_2g7d5 notranslate _o5iw8']"));
foreach (IWebElement option in displayedOptions)
{
string temp = option.GetAttribute("title");
following.Add(temp);
}
You're looking to get the a element's title attribute. The selenium IWebElement interface has a GetAttribute method you can use to get the title of your elements.
foreach (IWebElement option in displayedOptions)
{
following.Add(option.GetAttribute("title"));
}

C#: HttpCookie Content Setted in Index Page and then desapeared on all over the WebSite

I'm facing an issue using HttpCookie.
I'm building an Ecommerce and I'm trying to set Cookies for my Website.
There are three Cookies defined as describe bellow:
private static string cookienameCampanha = "WLC-Ecommerce-Campanha";
private static string cookienameUsuario = "WLC-Ecommerce-Usuario";
private static string cookienameRodape = "WLC-Ecommerce-Rodape";
All of then is used when HttpCookie is instantiated as bellow:
HttpCookie cookiehelper = new HttpCookie(cookienameCampanha);
HttpCookie cookiehelper = new HttpCookie(cookienameUsuario);
HttpCookie cookiehelper = new HttpCookie(cookienameRodape);
When user access index page for my Ecommerce, all those Cookies were setted. And they have specific definitions.
The third one, cookienameRodape, is used for setting content in footer and my web site shows those contents.
But after index page got fully reload and my footer listed all content, My Web Browser shows that all cookienameRodape content was erased and when I redirect the page to any other pages inside my site, all content is empty.
Something is weird, in DevTools using Chrome I can see other two Cookies Content setted and not erased, but "WLC-Ecommerce-Rodape" is not there even all content is listed in index page.
See the print below:
We can check My Index page and all content in my footer:
But when I try to navegate through my webSite, suddenly all content desapeared:
Additionaly, When always returned to index page, all Cookies are setted again and then all content inside footer are listed.
I tryed to search all over the SO and none of then suited me.
All Cookies are removed when user logged out. There is no any moment this happend.
After All content came from DataBase, Footer Contents were defined as below:
public static class AuxiliarCookieBLL
{
public static List<CampanhaInstitucionalModel> GetCampanhaInstitucional()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaInstitucional")))
{
List<CampanhaInstitucionalModel> CampanhaInstitucional = JsonConvert.DeserializeObject<List<CampanhaInstitucionalModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaInstitucional")));
return CampanhaInstitucional;
}
else
return new List<CampanhaInstitucionalModel>();
}
public static void SetCampanhaInstitucional(List<CampanhaInstitucionalModel> CampanhaInstitucional)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaInstitucional != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaInstitucional);
cookiehelper.AddToCookie("CampanhaInstitucional", HttpUtility.UrlEncode(campanha));
}
}
public static List<CampanhaAtendimentoModel> GetCampanhaAtendimento()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaAtendimento")))
{
List<CampanhaAtendimentoModel> CampanhaAtendimento = JsonConvert.DeserializeObject<List<CampanhaAtendimentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaAtendimento")));
return CampanhaAtendimento;
}
else
return new List<CampanhaAtendimentoModel>();
}
public static void SetCampanhaAtendimento(List<CampanhaAtendimentoModel> CampanhaAtendimento)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaAtendimento != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaAtendimento);
cookiehelper.AddToCookie("CampanhaAtendimento", HttpUtility.UrlEncode(campanha));
}
}
public static List<CampanhaCentralAtendimentoModel> GetCampanhaCentralAtendimento()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaCentralAtendimento")))
{
List<CampanhaCentralAtendimentoModel> CampanhaCentralAtendimento = JsonConvert.DeserializeObject<List<CampanhaCentralAtendimentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaCentralAtendimento")));
return CampanhaCentralAtendimento;
}
else
return new List<CampanhaCentralAtendimentoModel>();
}
public static void SetCampanhaCentralAtendimento(List<CampanhaCentralAtendimentoModel> CampanhaCentralAtendimento)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaCentralAtendimento != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaCentralAtendimento);
cookiehelper.AddToCookie("CampanhaCentralAtendimento", HttpUtility.UrlEncode(campanha));
}
}
public static List<CampanhaCertificadoModel> GetCampanhaCertificado()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaCertificado")))
{
List<CampanhaCertificadoModel> CampanhaCertificado = JsonConvert.DeserializeObject<List<CampanhaCertificadoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaCertificado")));
return CampanhaCertificado;
}
else
return new List<CampanhaCertificadoModel>();
}
public static void SetCampanhaCertificado(List<CampanhaCertificadoModel> CampanhaCertificado)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaCertificado != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaCertificado);
cookiehelper.AddToCookie("CampanhaCertificado", HttpUtility.UrlEncode(campanha));
}
}
public static List<CampanhaFormaPagamentoModel> GetCampanhaFormaPagamento()
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (!String.IsNullOrEmpty(cookiehelper.GetFromCookie("CampanhaFormaPagamento")))
{
List<CampanhaFormaPagamentoModel> CampanhaFormaPagamento = JsonConvert.DeserializeObject<List<CampanhaFormaPagamentoModel>>(HttpUtility.UrlDecode(cookiehelper.GetFromCookie("CampanhaFormaPagamento")));
return CampanhaFormaPagamento;
}
else
return new List<CampanhaFormaPagamentoModel>();
}
public static void SetCampanhaFormaPagamento(List<CampanhaFormaPagamentoModel> CampanhaFormaPagamento)
{
CookieHelper cookiehelper = new CookieHelper(cookienameRodape);
if (CampanhaFormaPagamento != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaFormaPagamento);
cookiehelper.AddToCookie("CampanhaFormaPagamento", HttpUtility.UrlEncode(campanha));
}
}
}
And now I can show my script footer page when I call all content and list then:
<div class="limite-layout">
<nav>
<ul class="col-xs-12 no-padding" id="navFooter">
<li class="col-md-2 institucional">
<div>
#{
rodape.Rodape.ListInstitucional = BLL.AuxiliarCookieBLL.GetCampanhaInstitucional();
if (rodape.Rodape.ListInstitucional.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Institucional</h6>
<ul id="Institucional" class="collapse">
#foreach (var item in rodape.Rodape.ListInstitucional)
{
#*<li>#item.Nome</li>*#
<li>#item.Nome</li>
}
</ul>
}
}
</div>
</li>
<li class="col-md-2 atendimento">
<div>
#{
rodape.Rodape.ListAtendimento = BLL.AuxiliarCookieBLL.GetCampanhaAtendimento();
if (rodape.Rodape.ListAtendimento.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Atendimento</h6>
<ul id="Atendimento" class="collapse">
#foreach (var item2 in rodape.Rodape.ListAtendimento)
{
<li>#item2.Nome</li>
}
</ul>
}
}
</div>
</li>
<li class="col-md-2 central-atendimento">
<div>
#{
rodape.Rodape.ListCentralAtendimento = BLL.AuxiliarCookieBLL.GetCampanhaCentralAtendimento();
if (rodape.Rodape.ListCentralAtendimento.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Central de Atendimento</h6>
<ul id="CentralAtendimento" class="collapse">
#foreach (var item3 in rodape.Rodape.ListCentralAtendimento)
{
<li>#item3.Nome</li>
}
</ul>
}
}
</div>
</li>
<li class="col-md-3">
<div class="certificados">
#{
rodape.Rodape.ListCertificado = BLL.AuxiliarCookieBLL.GetCampanhaCertificado();
if (rodape.Rodape.ListCertificado.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Certificados</h6>
<ul id="Certificados" class="collapse list-horizontal">
#foreach (var item5 in rodape.Rodape.ListCertificado)
{
#*<li><img alt="#item5.Nome" src="#item5.Descricao" /></li>*#
<li><img alt="#item5.Nome" src="~/Content/img/conteudo/certificados/ligodaddy.png" /></li>
<li><img alt="#item5.Nome" src="~/Content/img/conteudo/certificados/clearsale_logo.jpg" /></li>
<li><img alt="#item5.Nome" src="~/Content/img/conteudo/certificados/ABComm.png" /></li>
}
</ul>
}
}
</div>
<div class="pagamentos">
#{
rodape.Rodape.ListFormaPagamento = BLL.AuxiliarCookieBLL.GetCampanhaFormaPagamento();
if (rodape.Rodape.ListFormaPagamento.Count > 0)
{
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Formas de Pagamento</h6>
<ul id="FormaPagamento" class="collapse">
#foreach (var item4 in rodape.Rodape.ListFormaPagamento)
{
#*<li><img alt="Formas de Pagamento" src="#item4.URL" /></li>*#
<li><img alt="Formas de Pagamento" src="#item4.URL" /></li>
#*<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/mastercard.jpg" title="Mastercard"/></li>
<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/itau.jpg" title="Itaú"/></li>
<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/elo.jpg" title="Elo"/></li>
<li><img alt="Formas de Pagamento" src="~/Content/img/conteudo/formas-pagamento/boleto.jpg" title="Boleto"/></li>*#
}
</ul>
}
}
</div>
#if(BLL.AuxiliarCookieBLL.GetExibirRegulamento() == true)
{
<div class="footer-social">
<h6><i class="icon icon-right visible-xs-inline-block visible-sm-inline-block"></i>Redes Sociais</h6>
<ul id="Social" class="collapse list-horizontal">
<li>
<i class="icon icon-facebook"></i>
<i class="icon icon-twitter2"></i>
<i class="icon icon-gplus"></i>
</li>
</ul>
<div class="clearfix"></div>
</div>
}
</li>
<li class="col-md-3 ofertas">
<div>
<h6>Receba ofertas exclusivas no seu e-mail</h6>
<div class="form-group col-xs-12 no-padding">
<input type="text" name="Email" id="txtEmailNewsLetter" placeholder="Digite seu e-mail" />
</div>
<div class="form-group col-md-8 input-left">
<input type="text" name="Nome" id="txtNomeNewsLetter" placeholder="Digite seu nome" />
</div>
<div class="form-group col-md-4 no-padding container-btn-enviar text-right">
Enviar
</div>
<p id="erroNewsLetter" class="display-none no-margin-top">Verifique os campos digitados!</p>
<p id="msgOkNewsLetter" class="display-none no-margin-top">E-mail cadastrado.</p>
<p id="msgErroRequest" class="display-none no-margin-top">Erro ao cadastrar. Por favor tente novamente.</p>
<div class="clearfix"></div>
</div>
</li>
</ul>
</nav>
<div class="clearfix"></div>
</div>
EDIT
Here is CookieHelper code content:
There are two constructors and Property
//Constructors
public CookieHelper(String CookieName)
{
myCookieName = CookieName;
}
public CookieHelper(String CookieName, DateTime ExpiresDate)
{
myCookieName = CookieName;
dtExpires = ExpiresDate;
}
//Property
private static HttpCookie myCookie
{
get
{
return HttpContext.Current.Request.Cookies[myCookieName] != null ? HttpContext.Current.Request.Cookies[myCookieName] : NewCookie();
}
set
{
HttpContext.Current.Response.Cookies.Add(value);
}
}
And here is basic methods:
public void AddToCookie(String FieldName, String Value)
{
HttpCookie myHttpCookie = myCookie;
myHttpCookie[FieldName] = Value;
myCookie = myHttpCookie;
}
public void RemoveCookie()
{
HttpCookie myHttpCookie = myCookie;
myHttpCookie.Value = null;
myHttpCookie.Expires = DateTime.Now.Date.AddDays(-1);
myCookie = myHttpCookie;
}
private static HttpCookie NewCookie()
{
HttpCookie newcookie = new HttpCookie(myCookieName);
if(dtExpires != null)
newcookie.Expires = (DateTime)dtExpires;
HttpContext.Current.Response.Cookies.Add(newcookie);
return newcookie;
}
What could be happening?
All content inside this Cookie worked fine, and suddenly all Browsers are not stored this specific one.
Can any one help me with this problem?
If needs any further information, please advise me.
Not sure about your code in CookieHelper but I can't see that you'r setting an expiration or adding the cookie to the response. Those are two very important parts to using cookies so if they are missing, try to do something like this
public static void SetCampanhaInstitucional(List<CampanhaInstitucionalModel> CampanhaInstitucional)
{
if (CampanhaInstitucional != null)
{
string campanha = JsonConvert.SerializeObject(CampanhaInstitucional);
HttpCookie theCookie = new HttpCookie(cookienameRodape, campanha);
theCookie.Expires.AddDays(7); //Keep the cookie alive for 7 days
HttpContext.Response.Cookies.Add(theCookie); //add the cookie to the response
//alternatively you could also use
//HttpContext.Response.SetCookies(theCookie);
}
}
If your having trouble with using HttpContext.Response.Cookies.Add(theCookie); you might need to set the cookie using Response.SetCookie(theCookie) as per This answer to a cookie problem
Also, how much data are you storing?
Cookies are not ment to store alot of data and most browsers support up to 4096 bytes or 4kb. This is however for all cookies on the domain, so if you have 2 cookies using the 4kb, then adding another cookie will result the loss off cookies.
I can see from the screenshot that you are not using all of the available space, but as the Rodape cookie is not present, I have now idea of how big than one might be. Try just adding the Rodape cookie and see if it persists and check the size of it.
There are numerous possible causes for what you're seeing. To find the specific cause for your case, I would start by setting breakpoints in the code in any place where the value of the cookie gets set or reset. By running the code in a debugger, you can see if that code gets called at unexpected times. Repeat the steps to reproduce the problem, taking note of any unexpected calls to the code that change the cookie value. See what this reveals.

Recursively create accordion html from list of links in C#

I am scraping a remote page for links, which I have in a List. I am trying to get the list printed out as necessary for a jquery accordion. I have the html no problem, but my loops are off a bit and aren't nesting properly.
Here is an example of the List:
Heading 1
link1
link2
link3
Heading 2
link4
link5
link6
So here is how I need to get the html formatted:
<div data-role="collapsible" data-collapsed="true">
<h3>Heading 1</h3>
<p>
<ul>
<li>link1</li>
<li>link2</li>
<li>link3</li>
</ul>
</p>
</div>
<div data-role="collapsible" data-collapsed="true">
<h3>Heading 2</h3>
<p>
<ul>
<li>link4</li>
<li>link5</li>
<li>link6</li>
</ul>
</p>
</div>
And here is the code I have so far, it should be mentioned I am using the HTMLAgilityPack:
HtmlNodeCollection OneHome = document.DocumentNode.SelectNodes("//div[#id='accordion1']");
var OneHomelinks = OneHome.Descendants("a")
.Select(a => a.OuterHtml)
.ToList();
foreach (string link in OneHomelinks)
{
if (link.Contains('#'))
{
Response.Write("<div data-role=\"collapsible\" data-collapsed=\"true\">");
Response.Write("<h3>" + link + "</h3>");
Response.Write("<p>");
Response.Write("<ul>");
}
if (!link.Contains('#'))
{
Response.Write("<li>" + link + "</li>");
} else {
Response.Write("</ul>");
Response.Write("</p>");
Response.Write("</div>");
}
}
Basically I am trying to pull out the Headings by using the '#' in the href, and resetting the at that point - but something is off, the lists aren't being properly formed. Any help is super appreciated here!
CURRENT OUTPUT
<div data-role="collapsible" data-collapsed="true">
<h3>Heading 1</h3>
<p></p>
<ul></ul>
<p></p>
</div>
<li><a href="link1.html>link1</a></li>
<li><a href="link2.html>link2</a></li>
<li><a href="link3.html>link3</a></li>
<div data-role="collapsible" data-collapsed="true">
<h3>Heading 2</h3>
<p></p>
<ul></ul>
<p></p>
</div>
<li><a href="link4.html>link4</a></li>
<li><a href="link5.html>link5</a></li>
<li><a href="link6.html>link6</a></li>
Edit: Logic in the wrong spot, whoops!
Edit 2: Once more with logic placement.
I think this should work for you:
HtmlNodeCollection OneHome = document.DocumentNode.SelectNodes("//div[#id='accordion1']");
var OneHomelinks = OneHome.Descendants("a")
.Select(a => a.OuterHtml)
.ToList();
var headerCount = 0;
foreach (string link in OneHomelinks)
{
var prevCounter = headerCount;
if (link.Contains('#'))
{
headerCount++;
if (headerCount != 1 && headerCount > prevCounter) {
Response.Write("</ul>");
Response.Write("</p>");
Response.Write("</div>");
}
Response.Write("<div data-role=\"collapsible\" data-collapsed=\"true\">");
Response.Write("<h3>" + link + "</h3>");
Response.Write("<p>");
Response.Write("<ul>");
}
else {
Response.Write("<li>" + link + "</li>");
}
}
Response.Write("</ul>");
Response.Write("</p>");
Response.Write("</div>");

Categories