vb.net add html to aspx page dynamically - html

I have an aspx page with a sidebar on the left.
The sidebar shows from one to many tasks grouped by date.
I want to show a modal popup passing an ID when user clicks a task.
The sidebar is something like this:
01/09/2016
Go to the dentist
Meet with Anna
02/09/2016
blabla
03/09/2016
bla1
bla2
bla3
etc.
On page load I declare variables and query my database with this:
Dim elementoLi As String = "<li><h2><i class=""fa fa-cog fa-fw""></i>XXX</h2>YYY</li>"
Dim htmlTitle As String = "<div class=""title"">
<h1>XXX</h1>
</div><div class=""content""><ul>YYY</ul></div><br/>"
Dim htmlContent As String = ""
Dim htmlChiamateaperte As String = ""
Dim htmlfinale As String = ""
Dim chiamateAperte = From statoRic In
dbVulcano.StatoRic.Where(Function(s) s.RFStato >= 11 And s.RFStato <= 13 And s.Attuale = 1 And s.RFTecnico = rfTecnico)
From richiesta In
dbVulcano.Richieste.Where(Function(r) r.IDRic = statoRic.RFRic).DefaultIfEmpty()
From cliente In
dbVulcano.Clienti.Where(Function(c) c.IDCliente = richiesta.RFCliente).DefaultIfEmpty()
Select statoRic.RFRic, statoRic.RFStato, statoRic.Attuale, richiesta.Descr, cliente.RagSociale, statoRic.DataAss, statoRic.Data, dataf = If(statoRic.DataAss.HasValue, statoRic.DataAss, statoRic.Data)
Order By dataf Descending
Then I cycle to create the sidebar structure:
For Each item In chiamateAperte
Dim data1 = Format(item.dataf, "dd/MM/yyyy")
If htmlChiamateaperte.Contains(data1) = False Then
htmlChiamateaperte = htmlChiamateaperte & Replace(htmlTitle, "XXX", data1)
htmlContent = ""
End If
For Each item2 In chiamateAperte
Dim data2 = Format(item2.dataf, "dd/MM/yyyy")
If data2 = data1 Then
Dim rags, desc As String
desc = UppercaseFirstLetter(item2.Descr)
rags = item2.RagSociale
htmlContent = htmlContent & Replace(Replace(elementoLi, "XXX", rags), "YYY", desc)
End If
Next
htmlChiamateaperte = Replace(htmlChiamateaperte, "YYY", htmlContent)
Next
divChiamateAperte.InnerHtml = "<h1>CHIAMATE APERTE</h1><br /><br />" & htmlChiamateaperte
Basically I dinamically create a string that at the end is passed as html code. What I need is to add links in the "elementoLi" var so that, once the user click on the link, it opens a modal popup (and passes along an ID). How can I do that? Doesn't matter if I have to change all the code to create the structure. Thanks
EDIT 1:
This is the structure I need:
<div class="panel" runat="server" id="divChiamateAperte" autopostback="true">
<h1>CHIAMATE APERTE</h1><br /><br />
<div class="title"><h1>dd/mm/yyyy</h1>
</div>
<div class="content">
<ul>
<li><h2><i class="fa fa-cog fa-fw"></i> RAGIONE SOCIALE 1</h2> Descrizione 1</li>
<li><h2><i class="fa fa-cog fa-fw"></i> RAGIONE SOCIALE 2</h2> Descrizione 2</li>
</ul>
</div>
<br />
<div class="title"><h1>dd/mm/yyyy</h1>
</div>
<div class="content">
<ul>
<li><h2><i class="fa fa-cog fa-fw"></i> RAGIONE SOCIALE 1</h2> Descrizione 1</li>
<li><h2><i class="fa fa-cog fa-fw"></i> RAGIONE SOCIALE 2</h2> Descrizione 2</li>
</ul>
</div>
</div>
EDIT 2:
I made this example using the structure above and the repeater, but the problem I see to obtain the above (where the block made by div title to div content can be 1 to infinite) is that I need to repeat the repeater result from 1 to X (where x is the data read from db).
<%# Page Language="VB" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Repeater Example</title>
<script runat="server">
Sub Page_Load(Sender As Object, e As EventArgs)
If Not IsPostBack Then
Dim values As New ArrayList()
values.Add("Apple")
values.Add("Orange")
values.Add("Pear")
values.Add("Banana")
values.Add("Grape")
' Set the DataSource of the Repeater.
Repeater1.DataSource = values
Repeater1.DataBind()
End If
End Sub
</script>
</head>
<body>
<h3>Repeater Example</h3>
<form id="form1" runat="server">
<b>Repeater1:</b>
<br />
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<div class="title">
<h1>dd/mm/yyyy</h1>
</div>
<div class="content">
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<h2><i class="fa fa-cog fa-fw"></i><%# Container.DataItem %></h2>
Descrizione 1</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</div>
</FooterTemplate>
</asp:Repeater>
<br />
</form>
</body>
</html>

First of all, it is not recommended to use
Dim html as String = ""
html += .....
html += .....
this consume a lot of RAM on the server
Second, you may want to use the Repeater control if you are using .NET webform. Read more on the why on: http://blog.zay-dev.com/net-web-form-implementation-strategy-3-the-controls/
Example (.ASPX):
<asp:Repeater runat="server" ID="RepeaterCode">
<ItemTemplate>
<div>
<h1><asp:Literal runat="server" ID="LiteralHeader"/></h1>
<span class="<asp:Literal runat='server' ID='LiteralSpanClass'/>">
<asp:Literal runat="server" ID="LiteralSpanContent"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
.ASPX.VB:
Protected Sub Page_Load(sender as Object, e as EventArgs) Handles Me.Load
RepeaterCode.DataSource = Source
RepeaterCode.DataBind()
End Sub
Protected Sub RepeaterCode_ItemDataBound(sender as Object, e as RepeaterItemEventArgs) Handles RepeaterCode.ItemDataBound
If (TypeOf e.Item Is RepeaterItem) Then
Dim LiteralHeader as Literal = e.Item.FindControl("LiteralHeader")
If (LiteralHeader IsNot Nothing) Then LiteralHeader.Text = "Header"
End If
End Sub
Edit 1 -
ASPX:
<div class="panel" id="divChiamateAperte">
<h1>CHIAMATE APERTE</h1>
<br /><br />
<asp:Repeater runat="server" ID="RepeaterGroups" OnItemDataBound="RepeaterGroups_ItemDataBound">
<ItemTemplate>
<div class="title">
<h1>
<asp:Literal runat="server" ID="LiteralHeader"/>
</h1>
</div>
<div class="content">
<ul>
<asp:Repeater runat="server" ID="RepeaterItems" OnItemDataBound="RepeaterItems_ItemDataBound">
<ItemTemplate>
<li>
<h2>
<i class="fa fa-cog fa-fw"><i>
<asp:Literal runat="server ID="LiteralItemText"/>
</h2>
<a href="#" onclick="ShowModal($(this).attr("data-id"))" data-id="<asp:Literal runat='server' ID='LiteralID'/>">
<asp:Literal runat="server" ID="LiteralAnchorText"/>
</a>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
.ASPX.VB:
Protected Sub Page_Load(sender as Object, e as EventArgs) Handles Me.Load
If (Not Me.IsPostBack) Then
Dim dt as DataTable = Model.GetSideBarGroups()
RepeaterGroups.DataSource = dt
RepeaterGroups.DataBind()
End If
End Sub
Protected Sub RepeaterGroups_ItemDataBound(Sender As Object, e As RepeaterItemEventArgs)
If (TypeOf e.Item Is RepeaterItem AndAlso e.Item.DataItem IsNot Nothing) Then
Dim dr as DataRow = e.Item.DataItem
Dim GroupID as Integer = If(IsDBNull(dr("GroupID")), -1, Integer.Parse(dr("GroupID").ToString()))
Dim GroupDate as DateTime = If(IsDBNull(dr("GroupDate")), DateTime.Today, DateTime.Parse(dr("GroupDate").ToString()))
Dim dt as DataTable = Model.GetSideBarItems(GroupID)
Dim LiteralHeader as Literal = e.Item.FindControl("LiteralHeader")
Dim RepeaterItems as Repeater = e.Item.FindControl("RepeaterItems")
If (LiteralHeader IsNot Nothing) Then LiteralHeader.Text = GroupDate.ToString("dd/mm/yyyy")
If (RepeaterItems IsNot Nothing) Then
RepeaterItems.DataSource = dt
RepeaterItems.DataBind()
End If
End If
End Sub
Protected Sub RepeaterItems_ItemDataBound(Sender As Object, e As RepeaterItemEventArgs)
' To-Do
End Sub

Related

CSS selector QuerySelector alternative

I have searched a lot and a lot so as to find material about how to get meta data using XMLHTTP. And I think that's impossible to do that using the Early binding method. The only approach that will work is the late binding by CreateObject("HTMLFile") and dealing with that HTML which is late binding. The disadvantage of this approach is that it doesn't support the use of the QuerySelector or QuerySelectorAll..
Now I am trying to find alternative to this CSS selector .. without using the QuerySelector
Set post = .querySelector("table div span[itemprop='lowPrice']")
This arises an error .. and I can't find easier way to find the element
Here's the HTML content
<table class="p">
<tbody><tr>
<td class="foto">
<div class="foto">
<a href="https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/#gallery-open" target="_blank" class="gallery-link product-detail__gallery-link" onclick="dataLayer.push({'event':'sendEvent','event_category':'Product Detail - Desktop','event_action':'Gallery','event_label':'Otev\u0159en\u00ed galerie','event_value':0});">
<img src="https://im9.cz/iR/importprodukt-orig/4c2/4c2b1733c8b233edd5052d3063ac46d9--mmf250x250.jpg" alt="Brit Premium by Nature Adult L 15 kg" width="250" height="250" id="picture-main">
<span class="image-hover">
<span class="image-overlay"></span>
<span class="js-test-image-count-info image-count-info">Galerie <span class="picture-count">(2)</span></span>
</span>
<span class="product-detail__gallery-link__image__count-info">Galerie
<span class="product-detail__gallery-link__image__count-info__count">(2)</span>
</span>
</a>
<span>Top</span><strong>1.</strong>
<div class="poty-ico">
<img src="https://im9.cz/iR/recenze-externi/107.png" alt="Produkt Roku 2019" class="product-of-year-badge"></div>
</div>
</td>
<td>
<div class="main-info">
<div class="text-cover">
<div id="n649054946" data-id="649054946" class="item js-public-product-id">
<h2 itemprop="name">Brit Premium by Nature Adult L 15 kg</h2>
</div>
<div class="rating-box" itemprop="aggregateRating" itemscope="" itemtype="http://schema.org/AggregateRating">
<p class="eval">
<strong itemprop="ratingValue">95%</strong>
<a href="https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/pridat-uzivatelskou-recenzi/#section">
<span class="rating"><span class="hidden">Hodnocení produktu: 95%</span><span class="over" title="Hodnocení produktu: 95%"><span style="width: 75px;"></span></span></span>
</a>
</p>
<span class="hidden-microdata" itemprop="ratingCount">
456
</span>
<p class="review-count delimiter-blank">
<a href="https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/recenze/#section" class="gtm-header-link" data-gtm-link-description="Počet recenzí">
<span itemprop="reviewCount">344</span>
recenzí
</a>
</p>
<div class="cleaner"></div>
<p class="rating-box__item rating-box__favourite">
Přidat do oblíbených
</p>
<p id="cli649054946" class="rating-box__item rating-box__compare delimiter-blank cl-add">
<a class="checkbox gtm-header-link" data-gtm-link-description="Akce - porovnání" href="#" title="Porovnat">Přidat do porovnání</a>
</p>
<p class="delimiter-blank rating-box__item rating-box__price-watch js-price-watch-button">
<a href="#" title="Hlídat cenu" class="gtm-header-link" data-gtm-link-description="Akce - hlídat cenu">
Hlídat cenu
</a>
</p>
<p class="add-review rating-box__item rating-box__add-review delimiter-blank">
<a href="https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/pridat-uzivatelskou-recenzi/#section" class="gtm-header-link" data-gtm-link-description="Akce - přidat recenzi">
Přidat recenzi
</a>
</p>
</div>
<div id="top-shop-info" class="top-shop-info">
<div class="inner">
<div class="guar">
<div>
<img class="guar-badge" src="https://im9.cz/css-v2/images/guaranty-seal.png?1" alt="Garance nákupu - SpokojenyPes.cz" width="27" height="34">
</div>
</div>
<div class="shop-claim bold">
<strong>Produkt vám dodá:</strong>
</div>
<div class="shop-logo">
<a href="https://www.heureka.cz/exit/spokojenypes-cz/3180319922/?z=41" target="_blank" rel="nofollow noopener" class="gtm-header-link" data-gtm-link-description="Exit - produkt vám dodá">
<img src="https://im9.cz/iR/importobchod-orig/1983_logo--mmf130x40.png" alt="SpokojenyPes.cz" width="130" height="40">
</a>
</div>
<div class="recommendation">
<a href="https://obchody.heureka.cz/spokojenypes-cz/recenze/" class="gtm-header-link" data-gtm-link-description="Hodnocení - Produkt vám dodá">
99% zákazníků doporučuje obchod
</a>
</div>
<div class="delivery-info bold price-delivery-free">
Doprava zdarma
</div>
<div class="availability-info bold in-stock">
skladem
</div>
</div>
<a data-gtm-link-description="Další nabídky" id="top-shop-count-info" href="https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/porovnat-ceny/#section" class="top-shop-count-info box-active gtm-header-link">Dalších 134 nabídek od 728 Kč</a>
</div>
<p class="desc">
<span id="product-short-description">
Kompletní krmivo Brit Premium pro dospělé psy. Kuřecí receptura pro dospělé psy velkých plemen (25 - 45 kg).
<a id="product-short-description-button" href="https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/specifikace/#section" title="celá specifikace Brit Premium by Nature Adult L 15 kg">celá specifikace</a>
</span>
</p>
</div>
<div itemprop="offers" itemscope="" itemtype="http://schema.org/AggregateOffer" style="display:none">
<span itemprop="lowPrice">728.00</span>
<span itemprop="highPrice">1579.00</span>
<span itemprop="offerCount">135</span>
<link itemprop="availability" href="http://schema.org/InStock">
</div>
<div itemprop="offers" itemscope="" itemtype="http://schema.org/Offer" class="price-from shopping-cart">
<link itemprop="itemCondition" href="http://schema.org/OfferItemCondition" content="http://schema.org/NewCondition">
<link itemprop="availability" href="http://schema.org/InStock">
<link itemprop="category" href="http://schema.org/category" content="Hobby / Chovatelství / Pro psy / Krmivo pro psy">
<link itemprop="image" href="http://schema.org/image" content="https://im9.cz/iR/importprodukt-orig/4c2/4c2b1733c8b233edd5052d3063ac46d9.jpg">
<div class="top-left">
<div id="top-button" class="buy-click-observed">
<p class="buy">
<a href="#" class="flat-button flat-button--top-position flat-button--orange buy-btn hb hb-3180319922 js-top-pos-btn" data-cart-position="0">
<i class="ico basket"></i>
<i class="ico check"></i>
<span class="in">Koupit na Heurece</span>
<span class="in replace">Přidáno do košíku</span>
</a>
</p>
</div>
<div class="n" id="top-offer-price">
<p class="buy-price">
<span itemprop="price" class="js-top-price" content="839.00">839 Kč</span>
<span class="price-vat-title small">s DPH</span>
<span itemprop="priceCurrency" content="CZK"></span>
</p>
</div>
<div class="clear"></div>
<div class="js-top-gifts-info top-shop-gifts-info-box">
</div>
</div>
<div class="clear"></div>
<div class="clear"></div>
</div>
<span id="new-pd"></span>
<script>
(function() {
loadScript("https:\/\/im9.cz\/js\/cache\/7e39f733-1-42bd9e7837b830d87e1af94da6d0e4a82055c56f.hash.js", function () {
var productHeadObserver = new ProductHeadObserver({ 'topShortDescElm': $('product-short-description'), 'topShopBox': $('top-shop-info'), 'maxOfferNameLength': 90 });
productHeadObserver.oneOfferInit();
});
H.Awards._reviewClick($$('#awards-list span.pa'));
var notSelectedCallback = function() {
if ('undefined' != typeof H.ShoppingCartHelper.BuyMoreOptions &&
typeof H.ShoppingCartHelper.BuyMoreOptions.buyClickNotSelectedCallback == 'function') {
H.ShoppingCartHelper.BuyMoreOptions.buyClickNotSelectedCallback();
}
};
H.ShoppingCartHelper.observeBuyClick($('top-button'), new H.ShoppingCart(), notSelectedCallback, 'js-top-pos-btn');
})();
</script>
<div class="clear"></div>
</div>
</td>
</tr>
</tbody></table>
This is the whole HTML
https://pastebin.com/Dgu1wk2b
Here's the code till now
Sub MyTest()
Dim source As Object
Dim obj As Object
Dim resp As String
Dim post As Object
Dim a, i As Long
With CreateObject("MSXML2.xmlHttp")
.Open "GET", "https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/specifikace/#section", False
.send
resp = .responseText
End With
With CreateObject("HTMLFile")
.write resp
Set post = .getElementsByTagName("meta")
For i = 0 To post.Length - 1
On Error Resume Next
Debug.Print post.item(i).getAttribute("name")
If post.item(i).getAttribute("name") = "gtm:product_id" Then
Cells(2, 1).Value = post.item(i).Value
End If
If post.item(i).getAttribute("name") = "gtm:product_name" Then
Cells(2, 3).Value = post.item(i).Value
End If
If post.item(i).getAttribute("name") = "gtm:product_brand" Then
Cells(2, 4).Value = post.item(i).Value
End If
On Error GoTo 0
Next i
Set post = Nothing
Set post = .getElementsByTagName("link")
For i = 0 To post.Length - 1
On Error Resume Next
If post.item(i).getAttribute("rel") = "canonical" Then
Cells(2, 2).Value = post.item(i).href
End If
On Error GoTo 0
Next i
'I am stuck here
'Set post = .querySelector("table div span[itemprop='lowPrice']")
'Debug.Print .getElementsByTagName("table")(0).innerHTML
End With
End Sub
As you have discovered HEAD tag info (where meta stuff lives) is stripped out when you use document.body.innerHTML = .responseText with early-bound MSHTML.HTMLDocument. Kinda what you would expect considering what you are populating (document.body). That is why you are unable to select the meta info. With your late bound HTMLFile (where you can't use querySelector) you are using .write method which is writing to your document (HTMLFile) and thereby retaining the HEAD info.
You need to ensure that the HEAD info ends up within BODY tags. Either as part of response body or extracted HEAD concatenated with new BODY tags and written to HTMLDocument if wishing to use early binding.
E.g. for clarity I am writing HEAD info between BODY tags only (Without rest of existing response)
Option Explicit
Public Sub MetaInfoEarlyBound()
Dim html As MSHTML.HTMLDocument, htmlHead As MSHTML.HTMLDocument, xhr As MSXML2.XMLHTTP60
Dim re As VBScript_RegExp_55.RegExp
Set htmlHead = New MSHTML.HTMLDocument
Set html = New MSHTML.HTMLDocument
Set xhr = New MSXML2.XMLHTTP60
Set re = New VBScript_RegExp_55.RegExp
re.Pattern = "<head>([\s\S]+)<\/head>"
With xhr
.Open "GET", "https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/specifikace/#section", False
.send
htmlHead.body.innerHTML = Replace$(Replace$(re.Execute(.responseText)(0), "<head>", "<body>"), "</head>", "</body>")
html.body.innerHTML = .responseText
End With
Debug.Print htmlHead.querySelector("[name='gtm:product_price']").Value
Debug.Print html.querySelector("[itemprop=lowPrice]").innerText
End Sub
As an aside, I add two shorter methods (than current other answer) to achieve your goal with late-bound. Note I have commented one out.
Public Sub MetaInfoLateBound()
Dim resp As String
With CreateObject("MSXML2.xmlHttp")
.Open "GET", "https://krmivo-psy.heureka.cz/brit-premium-by-nature-adult-l-15-kg/specifikace/#section", False
.send
resp = .responseText
End With
With CreateObject("HTMLFile")
.write resp
' Dim post As Object
'
' Set post = .getElementById("new-pd")
' Debug.Print post.PreviousSibling.PreviousSibling.getElementsByTagName("span")(0).innertext
'
Dim metas As Object, i As Long
Set metas = .getElementsByTagName("meta")
For i = 0 To metas.Length - 1
If metas.Item(i).Name = "gtm:product_price" Then
Debug.Print metas.Item(i).Value
Exit For
End If
Next
End With
End Sub
Try this:
With CreateObject("HTMLFile")
.Open
.write resp
.Close
For Each tbl In .getElementsByTagName("table")
For Each dv In tbl.getElementsByTagName("div")
If dv.getattribute("itemprop") = "offers" Then '<<EDIT
For Each spn In dv.getElementsByTagName("span")
attr = ""
attr = spn.getattribute("itemprop")
If Len(attr) > 0 Then
If attr = "lowPrice" Then
Debug.Print spn.outerhtml
Debug.Print spn.innerText
End If
End If
Next spn
End If
Next dv
Next tbl
End With

how to add Button Click Event in asp.net with vb

I have problem with onclick event. Here is an example which is similar to my project
HTML
<%# Page Language="VB" AutoEventWireup="true" CodeFile="Example.aspx.vb" Inherits="Example" %>
<html>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<br />
<asp:Label ID="label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
VB
Partial Class Example
Inherits System.Web.UI.Page
Dim No_of_Animals As Integer = 6 ' Number of Animals
Dim Cage(No_of_Animals) As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
label1.Text = " Animal released: " & Session.Item("AnimalReleased")
Cage(0) = "Cow"
Cage(1) = "Bat"
Cage(2) = "Dog"
Cage(3) = "Cat"
Cage(4) = "Snake"
Cage(5) = "Pig"
Dim html As New StringBuilder()
html.Append("<table>")
For Animal = 1 To No_of_Animals
html.Append("<tr><td>Cage " & Animal & " : </td>")
html.Append("<td> " & Cage(Animal - 1) & "</td>")
html.Append("<td><button runat=""server"" OnServerClick=""DisplayAnimal(" & Animal - 1 & ")"">Release</button></td></tr>")
Next
html.Append("</table>")
PlaceHolder1.Controls.Add(New Literal() With {.Text = html.ToString()})
End Sub
Public Sub DisplayAnimal(ByVal CageNo As Integer)
Session.Item("AnimalReleased") = Cage(CageNo)
End Sub
End Class
After I click a button the page will just refresh but session.item("AnimalRelease") was never given a value.
I'm suspecting onclick is not functioning well.
According to MSDN, the OnServerClick should be all lower case: "onserverclick".

Render Divs with DataSet content including Columns

I am struggling to render my DataSet contents into DIV tags with column names as headers.
I am trying to get it within a structure like so:
<div class="dataset">
<div class="dsheader">
<div class="dscell"><h6>Staff Name</h6></div>
<div class="dscell"><h6>Accrued Hours</h6></div>
<div class="dscell"><h6>Date Accrued</h6></div>
</div>
<div class="dsrow">
<div class="dscell"><p>1</p></div>
<div class="dscell"><p>2</p></div>
<div class="dscell"><p>3</p></div>
</div>
<div class="clearfix"/>
</div>
I have no idea how to start so I started the easy way and rendered the data into a table:
Dim r As DataRow
Dim dvCont As New HtmlGenericControl
Dim dvHead As New HtmlGenericControl
Dim dvRow As New HtmlGenericControl
Dim dvCell As HtmlGenericControl
For i As Integer = 0 To DataTable.Rows.Count - 1
Dim myRow As New HtmlTableRow
Dim divrow As New HtmlGenericControl
Dim divcell As New HtmlGenericControl
Dim StaffMemberCell As New HtmlTableCell
Dim LieuTypeCell As New HtmlTableCell
Dim LieuDateCell As New HtmlTableCell
Dim LieuDetailsCell As New HtmlTableCell
StaffMemberCell.InnerHtml = DataTable.Rows(i).Item("staff_member").ToString
myRow.Cells.Add(StaffMemberCell)
LieuTypeCell.InnerHtml = DataTable.Rows(i).Item("lieu_type").ToString
myRow.Cells.Add(LieuTypeCell)
LieuDateCell.InnerHtml = DataTable.Rows(i).Item("lieu_date").ToString
myRow.Cells.Add(LieuDateCell)
LieuDetailsCell.InnerHtml = DataTable.Rows(i).Item("lieu_details").ToString
myRow.Cells.Add(LieuDetailsCell)
lieuTable.Rows.Add(myRow)
Next
Where do I go from here?
I know to add runat="server" to DIV tags on the ASPX page.
<div id="dvContainer" class="dataset" runat="server">
<div id="dvContHeader" class="dsheader" runat="server">
<div id="dvContCell" class="dscell" runat="server"><h6>Header</h6></div>
<div id="Div1" class="dscell" runat="server"><h6>Header</h6></div>
<div id="Div2" class="dscell" runat="server"><h6>Header</h6></div>
</div>
<div id="dvRow" class="dsrow" runat="server"><p>data1</p></div>
<div id="dvContCell" class="dsrow" runat="server"><p>data1</p></div>
<div id="Div4" class="dsrow" runat="server"><p>data1</p></div>
<div id="Div5" class="dsrow" runat="server"><p>data1</p></div>
</div>
</div>
Another issue I have is do I have to explicitly state the div within the ASPX doc? See below. I see an issue with using the ID tags multiple times.
I achieved the result I was looking for by using a repeater.
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<div class="dsDataSet">
<div class="dsheader">
<div class="dscell"><h6>Staff Name</h6></div>
<div class="dscell"><h6>Accrued Hours</h6></div>
<div class="dscell"><h6>Date Accrued</h6></div>
</div>
</HeaderTemplate>
<ItemTemplate>
<div class="dsrow">
<div class="dscell"><p><%# Eval("Staff_member")%></p></div>
<div class="dscell"><p><%# Eval("Num_Hours")%></p></div>
<div class="dscell"><p><%# Format(Eval("Lieu_Date"), "dd-MM-yyyy")%></p></div>
</div>
</ItemTemplate>
<FooterTemplate>
<div class="clearfix"/>
</div>
</FooterTemplate>
</asp:Repeater>

Convert String into Div Object in vb.net/asp

I have a bit of a difficult problem which I can't seem to find out how to solve.
Basically, I have a couple tables on my database which, identify, by client, which divs IDs the client has access to, by using the tab
So I have a table which identifies the divs by their ID, by using the table index:
id | id_div
0 | D0
1 | D1
(and so on..)
And then another one which has only the clients ID and the divs (identified by the "id" field) he has access to:
client_id | div_id
29 | 0
29 | 1
(and so on..)
Then I'm cross referencing which divs should be visible and which should not.
The problem is I am getting the divs id as a string and in order to be able to tell in code-behind to set the visibility to false I need to reference the div in itself..
A sample:
<dx:TabPage Name="tabServico" Text="<%$ Resources:InterfaceGenerica, lblServico %>">
<ContentCollection>
<dx:ContentControl>
<div class="conteudo_pagina_tab">
<asp:HiddenField ID="hidID" runat="server" Value="0" EnableViewState="true" />
<asp:HiddenField ID="hidIdCliente" runat="server" Value="0" EnableViewState="true"/>
<div id="D0" runat="server">
<div class="cols coluna1">
<asp:Literal ID="litClientes" runat="server" Text="<%$ Resources:InterfaceGenerica, lblCliente %>"></asp:Literal>
</div>
<div class="cols coluna2-4">
<dx:ASPxComboBox ID="cboClientes" runat="server" HelpText="" ValueField="id_cliente" TextField="nome_completo" SelectedValue="" Width="100%" AutoPostBack="true"></dx:ASPxComboBox>
</div>
</div>
<clear></clear>
<div id="D1" runat="server">
<div class="cols coluna1">
<asp:Literal ID="litTipoOperacao" runat="server" Text="<%$ Resources:InterfaceGenerica, lblOperacao %>"></asp:Literal>
</div>
<div class="cols coluna2-4">
<dx:ASPxComboBox ID="cboTipoOperacao" runat="server" Width="100%" HelpText="" ValueField="id_operacoes" TextField="nome" SelectedValue="" AutoPostBack="true">
</dx:ASPxComboBox>
</div>
</div>
<clear></clear>
<div id="D2" runat="server">
<div class="cols coluna1">
<asp:Literal ID="litTipoServs" runat="server" Text="<%$ Resources:InterfaceGenerica, lblTipoServico %>"></asp:Literal>
</div>
<div class="cols coluna2-4">
<dx:ASPxComboBox ID="cboTipoServs" runat="server" HelpText="" ValueField="id_tipo_servs" TextField="nome" SelectedValue="" AutoPostBack="true" Width="100%"></dx:ASPxComboBox>
</div>
</div>
<div id="D3" runat="server">
<div class="cols coluna5">
<asp:Literal ID="litSubTipoServs" runat="server" Text="<%$ Resources:InterfaceGenerica, lblSubtipoServico %>"></asp:Literal>
</div>
<div class="cols coluna6-8">
<dx:ASPxComboBox ID="cboSubTipoServs" runat="server" HelpText="" ValueField="id_tipo_subtipos" TextField="nome" SelectedValue=""></dx:ASPxComboBox>
</div>
</div>
And in code behind I have:
Dim cross As New Hashtable()
Dim divsCliente() As String
Dim lstDivs As List(Of campos_agd_form)
lstDivs = campos_agd_form_mapper.CarregarDivs()
If lstDivs IsNot Nothing Then
For Each i In lstDivs
cross.Add(i.id, i.id_div)
Next
End If
Dim lstDivsCliente As List(Of clientes_campos_agd)
lstDivsCliente = clientes_campos_agd_mapper.CarregarCamposCliente(guser.id)
If lstDivsCliente IsNot Nothing Then
divsCliente = (lstDivsCliente.Item(0).id_campos_enum).Split(",")
End If
'Dim divsCliente() As Integer = Convert.ToInt32((lstDivsCliente.id_divs).Split(","))
For Each item In cross
For Each i In divsCliente
If item.Key = Convert.ToInt32(i) Then
Dim div As System.Web.UI.HtmlControls.HtmlGenericControl
div = TryCast(item.Value, System.Web.UI.HtmlControls.HtmlGenericControl)
div.Visible = False
End If
Next
Next
As I was already expecting I can't convert a string into a HtmlObject so what I need to do is to find an object by it's id (the string), without having to go through the parent-object (basically, search the whole document, like one would do with javascript with a getElementById)
How can this be accomplished?
The framework I'm using is .NET 4.0
I Recommend the following approach.
You need to know which information to show to each user, so you might want to store this in session for example (Global.asax):
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fetch from DB
Session("Rights") = {"MyID1", "MyID3"}
End Sub
Then create a base user control that checks from the session if it's id is in the list of the rights the user has. If not, the control will automatically hide it self:
Imports System.Linq
Public MustInherit Class MyBaseControl
Inherits System.Web.UI.UserControl
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
If Page.IsPostBack Then Return
Dim rights As String() = CType(Session("Rights"), String())
If Not rights.Any((Function(s) s = Me.ID)) Then Me.Visible = False
End Sub
End Class
Then create x number of content controls that inherit from this base control. These controls can have totally different content, but consider making as few as possible, since your D0, D1 etc seem to have almost same content. So just customize the control to handle different texts and values:
Public Class MyControl1
Inherits MyBaseControl
End Class
Then on the page you will have as many of these controls as needed:
<div>
<uc1:MyControl1 ID="MyID1" runat="server" />
<uc2:MyControl2 ID="MyID2" runat="server" />
<uc3:MyControl3 ID="MyID3" runat="server" />
</div>
Hope this helps.
So, I ended up doing things a little differently.
Basically I'm using a ClientScriptManager, and constructing an array with the elements to hide. (Which is then passed to the client side).
So the function now looks like this:
Private Sub ManipulaFormCliente()
Dim cross As New Hashtable()
Dim divsCliente() As String = New String() {}
Dim aux() As String = New String() {}
Dim cs As ClientScriptManager = Page.ClientScript
Dim lstDivs As List(Of campos_agd_form)
lstDivs = campos_agd_form_mapper.CarregarDivs()
If lstDivs IsNot Nothing Then
For Each i In lstDivs
cross.Add(i.id, i.id_div)
Next
End If
Dim lstDivsCliente As List(Of clientes_campos_agd)
lstDivsCliente = clientes_campos_agd_mapper.CarregarCamposCliente(" id_cliente = " & Convert.ToInt32(hidIdCliente.Value))
If lstDivsCliente IsNot Nothing Then
If lstDivsCliente.Count <> 0 Then
divsCliente = (lstDivsCliente.Item(0).id_campos_enum).Split(",")
End If
End If
For Each item In cross
For Each i In divsCliente
If item.Key = Convert.ToInt32(i) Then
cs.RegisterArrayDeclaration("divsCliente", "'" & item.Value & "'")
End If
Next
Next
End Sub
Then, on the client side I made a function which runs once the window has loaded, and uses the array constructed on code-behind to apply a css "display: none" on the divs whose IDs get passed on the array.
The code is the following:
window.onload = function hideFields() {
if (divsCliente.length > 0) {
for (var i = 0; i < divsCliente.length; i++) {
document.getElementById(divsCliente[i]).style.display = 'none';
}
}
}
This implements the behaviour desired: Whenever there's a postback (and respective load) this function is run, hiding the required divs/fields.
As a final touch, I had to add the 'clientidmode = "static"' attribute to the divs, in order to get the getElementById() function to work properly (according to the data in the DB)
I hope this helps anyone in need of a similar solution.

repeater control with ajax update panel for Paging

I have change my code. I add the updatepanel and the link buttons
Markup
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:LinkButton ID="btnPrev" runat="server" OnClick="btnPrev_Click">PrevButton</asp:LinkButton>
<asp:TextBox id="txtHidden" style="width: 28px" value="1" runat="server" />
<asp:LinkButton ID="btnNext" runat="server" OnClick="btnNext_Click">NextButton</asp:LinkButton>
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<div class="latnewstitle">
Date:</div>
<%#DataBinder.Eval(Container.DataItem, "date")%><br />
<div class="latnewstitle">
title:</div>
<div class="latnewscontent">
<%#DataBinder.Eval(Container.DataItem, "title")%></div>
<asp:HyperLink ID="lnkDetails" runat="server" NavigateUrl='<%# Eval("item_ID", "~/Details.aspx?ID={0}") %>'>See Details</asp:HyperLink>
<br />
<br />
<hr width="100px" />
<br />
</ItemTemplate>
</asp:Repeater>
</div>
</ContentTemplate>
</asp:UpdatePanel>
my code behind
Public Property PgNum() As Integer
Get
If ViewState("PgNum") IsNot Nothing Then
Return Convert.ToInt32(ViewState("PgNum"))
Else
Return 0
End If
End Get
Set(value As Integer)
ViewState("PgNum") = value
End Set
End Property
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not Page.IsPostBack Then
bindrepeater()
End If
End Sub
I add the bindrepeater sub so bind datato the repeater
Protected Sub bindrepeater()
Dim strsql As String = "SELECT * FROM news ORDER BY news.item_ID DESC"
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings("mycon").ToString
sqlconn.Open()
Dim cmd As New SqlCommand(strsql, sqlconn)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
cnt = ds.Tables(0).Rows.Count
'Dim table As New DataTable()
'da.Fill(table)
Dim pds As New PagedDataSource()
pds.DataSource = ds.Tables(0).DefaultView
pds.AllowPaging = True
pds.PageSize = 5
pds.CurrentPageIndex = PgNum
txtHidden.Text = PgNum
Dim vcnt As Integer = cnt / pds.PageSize
If PgNum < 1 Then
btnPrev.Visible = False
ElseIf PgNum > 0 Then
btnPrev.Visible = True
End If
If PgNum = vcnt Then
btnNext.Visible = False
ElseIf PgNum < vcnt Then
btnNext.Visible = True
End If
Repeater1.DataSource = pds
Repeater1.DataBind()
sqlconn.Close()
End Sub
'My paging buttons
Protected Sub btnNext_Click(sender As Object, e As System.EventArgs) Handles btnNext.Click
PgNum += 1
bindrepeater()
End Sub
Protected Sub btnPrev_Click(sender As Object, e As System.EventArgs) Handles btnPrev.Click
PgNum -= 1
bindrepeater()
End Sub
Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
bindrepeater()
End Sub
My problem is that my next button goes always +2 and the previous button -2.
Thank you