Answered by:
Filling the existening unordered list <ul> from database during runtime

Question
-
User-786564416 posted
I have the page that I use to deal with tags and store it back in the database [PostingsTags]:
<%@ Page Title="" Language="VB" ClientIDMode="Static" MasterPageFile="~/MasterPages/MyMasterPage.master" AutoEventWireup="false" CodeFile="Tag.aspx.vb" Inherits="NewPosting_Tag" MaintainScrollPositionOnPostback="true" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> <style type="text/css"> .MainFieldsDivStyle { border-color: Black; width: 70%; border-style: solid; margin-top: 22px; background-color:#C9DCF2; /*opacity: 0.8;*/ -moz-border-radius: 15px; -webkit-border-radius: 15px; border-radius: 15px; } .ErrorMessage { color: red; text-align: right; font-family: sc_AMEEN; font-style: normal; font-size: 28px; margin-left: 21px; } .CellStyle { border: 1px solid Black; background-color:#A1C1E6; width:20%; text-align: right; } .UpperMargin { margin-top:0px; margin-right:0px; } .Buttonout { cursor:default; -moz-border-radius: 15px; -webkit-border-radius: 15px; border-radius: 15px; } .Buttonhover { cursor:pointer; -moz-border-radius: 15px; -webkit-border-radius: 15px; border-radius: 15px; } #overlay { ; z-index: 99; top: 0px; left: 0px; background-color: #f8f8f8; width: 100%; height: 100%; filter: Alpha(Opacity=90); opacity: 0.9; -moz-opacity: 0.9; } #theprogress { background-color: #fff; border:1px none #ccc; padding:10px; width: 300px; height: 30px; line-height:30px; text-align: center; filter: Alpha(Opacity=100); opacity: 1; -moz-opacity: 1; } #modalprogress { ; top: 40%; left: 50%; margin: -11px 0 0 -150px; color: #990000; font-weight:bold; font-size:28px; font-family:SC_AMEEN; } .TagsULClass { text-align:right; } .auto-style1 { height: 37px; } </style> <link rel="stylesheet" type="text/css" href="<%= ResolveUrl("~/jquery/js/jquery-ui.css")%>"/> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css" /> <link rel="stylesheet" type="text/css" href="<%= ResolveUrl("~/jquery/js/jquery.tagit.css")%>"/> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="CpMainContent" Runat="Server"> <asp:toolkitscriptmanager ID="ScriptManager1" runat="server" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script> <script src="<%=ResolveUrl("~/jquery/js/tag-it.js") %>" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { var data = '<%= GetDataList() %>'; //get the available tags from code behind method. var datalist = data.split(","); //change the data to array $("#myTags").tagit({ availableTags: datalist }); $("#btnSubmit").click(function () { //event.preventDefault(); var str = $("#myTags").tagit("assignedTags"); //get the entered/selected tags. $("#hidSelectedValue").val(str); //use a hiddenfield to store the tags, then get it from code behind. }); }); </script> <div id="MainDiv" class="MainFieldsDivStyle"> <ul id="myTags" dir="rtl" class="auto-style1"> <!-- Existing list items will be pre-added to the tags --> </ul> <asp:HiddenField ID="hidSelectedValue" ClientIDMode="Static" runat="server" Value="" /> <asp:Button ID="btnSubmit" ClientIDMode="Static" runat="server" Text="Submit" OnClick="btnSubmit_Click" /> <asp:Label ID="lblOutput" runat="server" Visible="False"></asp:Label> </div> </asp:Content>
Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Imports System.Diagnostics Imports System.Net Imports System.Net.Mail Imports System.Web Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.Services Imports System.Text Imports System.String Partial Class NewPosting_Tag Inherits System.Web.UI.Page Public Shared querystring As String Public Shared EnteredTags As String Public Shared UserName As String
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click lblOutput.Text = hidSelectedValue.Value EnteredTags = hidSelectedValue.Value If Len(EnteredTags) > 0 Then Dim s As String = EnteredTags ' Split string based on comma Dim words As String() = s.Split(New Char() {","c}) ' Use For Each loop over words and display them Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString Using connection As New SqlConnection(conString) connection.Open() querystring = "DELETE FROM PostingsTags WHERE (RefNo=@RNo)" Dim ClearOldRecords As New SqlCommand(querystring, connection) ClearOldRecords.Parameters.Add("@RNo", SqlDbType.NVarChar) ClearOldRecords.Parameters("@RNo").Value = Session("LetterID") ClearOldRecords.ExecuteNonQuery() End Using Dim word As String For Each word In words AddNewTag(word) Next End If End Sub 'get the data list, used to populate the autocomplete available tags. Public Shared Function GetDataList() As String Dim StoredTagsList As SqlDataReader Dim datalist As String Dim data As List(Of String) = New List(Of String)() Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString Using connection As New SqlConnection(conString) connection.Open() querystring = "SELECT DISTINCT KeyTag FROM PostingsTags" Dim ExtractTagsList As New SqlCommand(querystring, connection) StoredTagsList = ExtractTagsList.ExecuteReader() If StoredTagsList.HasRows Then Do While StoredTagsList.Read() If StoredTagsList(0) <> "" Then data.Add(StoredTagsList(0)) End If Loop End If End Using datalist = String.Join(",", data) Return datalist End Function Public Sub AddNewTag(ByVal Tag As String) Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString Using connection As New SqlConnection(conString) connection.Open() querystring = "INSERT INTO PostingsTags(RefNo,KeyTag) VALUES(@RNo,@Tag)" Dim InsertNewTag As New SqlCommand(querystring, connection) InsertNewTag.Parameters.Add("@RNo", SqlDbType.NVarChar) InsertNewTag.Parameters("@RNo").Value = Session("LetterID") InsertNewTag.Parameters.Add("@Tag", SqlDbType.NVarChar) InsertNewTag.Parameters("@Tag").Value = Tag InsertNewTag.ExecuteNonQuery() End Using End Sub Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Session("UserName") = "" Then Response.Redirect("~\Logon\LogonScreen.aspx") End If UserName = Session("username") End Sub End ClassWhat I want is that when the Page loaded, I want to display with all the distinct KeyTag from the [PostingsTags] table WHERE the RefNo=session("LetterID). I want the displayed it in the <ul> in such a way exactly as tags shown on the image below. for example, If the stored tags in the [PostingsTags] table are: United_Kingdom,Aberdeen, Scotland, I want to show it as shown below. I can also add more tags, or delete any of the existence three tags.
How to perform this by code?
Monday, April 1, 2019 4:02 PM
Answers
-
User-893317190 posted
Hi alihusain_77 ,
It seems you are using jqueryui plugin tags.
You could use a list which stores values at code behind and render the list as ul at aspx.
Because you want to combine insert and delete function in the ul , I suggest you could record original data in a hidden field.
When the user click submit , get the submitted data to compare with original data so that you could know what to delete and what to insert.
Below is my code.
<head runat="server"> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script> <script src="../Scripts/tag-it.js"></script> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css" /> <link href="../Content/jquery.tagit.css" rel="stylesheet" /> </head> <body> <form id="form1" runat="server"> <ul id="myTags">
<!--render the data--> <% For Each tag In tags %> <li> <%=tag %></li> <% Next %> </ul> <asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" /> <asp:HiddenField ID="HiddenField1" runat="server" /> <script type="text/javascript"> $(document).ready(function() { $("#myTags").tagit(); // store the original data and assign the original data to a hidden field
// all the original data is stored in input whose name is tags var tagArr = []; $.each($("input[name=tags]"), function (index, ele) { tagArr.push(ele.value); }) $("#<%= HiddenField1.ClientID%>").val(tagArr.join(",")) }); </script> </form> </body>Code behind.
Inherits System.Web.UI.Page Private constr As String = ConfigurationManager.ConnectionStrings("EntityDb").ConnectionString Public tags As List(Of String) = New List(Of String) Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then Using con As SqlConnection = New SqlConnection(constr) ' select all the keytag from database and save value in tags Using com As SqlCommand = New SqlCommand("select keytag from postingsTags where Refno=@no ", con) con.Open() com.Parameters.AddWithValue("no", "id1") 'please change your id1 to your sessionvalue Using reader As SqlDataReader = com.ExecuteReader() If reader.HasRows Then While reader.Read() tags.Add(reader.GetString(0)) End While End If End Using End Using End Using End If End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Dim newTags = Request.Form("tags").Split(","c) ' get all the newTags Dim oldTags = HiddenField1.Value.Split(","c) ' get original oldTages Dim valuesToDelete = oldTags.Except(newTags).Distinct().ToList() ' get values to delete
' Except will get all the values which is in oldTags and is not in newTags Dim valuesToInsert = newTags.Except(oldTags).Distinct().ToList() ' get values to insert ' Except will get all the values which is in newTags and is not in oldTags
If valuesToDelete.Count > 0 Then Dim deleteSql = "delete from postingstags where keyTag in (" 'splice string to get the final deleteSql Using con As SqlConnection = New SqlConnection(constr) Using com As SqlCommand = New SqlCommand("", con)
'loop through valuesToDelete For index = 0 To valuesToDelete.Count - 1 If index = 0 Then
'add every delete parameter to sql deleteSql += "@parameter" & index ' Else deleteSql += ",@parameter" & index End If
' add value to every delete parameter com.Parameters.AddWithValue("parameter" & index, valuesToDelete(index)) Next deleteSql += ")" com.CommandText = deleteSql con.Open() Response.Write("you have deleted " & com.ExecuteNonQuery().ToString() & " record") End Using End Using End If If valuesToInsert.Count > 0 Then Dim insertSql = "insert into postingstags (RefNo,KeyTag) values " Using con As SqlConnection = New SqlConnection(constr) Using com As SqlCommand = New SqlCommand("", con)
'loop through every insert parameter For index = 0 To valuesToInsert.Count - 1
'add every insert parameter to sql If index = 0 Then insertSql += "(@RefNo,@parameter" & index.ToString() & ")" Else insertSql += ",(@RefNo,@parameter" & index.ToString() & ")" End If
'assign value to every insert parameter com.Parameters.AddWithValue("parameter" & index, valuesToInsert(index)) Next com.Parameters.AddWithValue("RefNo", "id1") com.CommandText = insertSql con.Open() Response.Write("<br/>you have inserted " & com.ExecuteNonQuery().ToString() & " record") End Using End Using End If ' reselect Using con As SqlConnection = New SqlConnection(constr) Using com As SqlCommand = New SqlCommand("select keytag from postingsTags where Refno=@no ", con) con.Open() com.Parameters.AddWithValue("no", "id1") Using reader As SqlDataReader = com.ExecuteReader() If reader.HasRows Then While reader.Read() tags.Add(reader.GetString(0)) End While End If End Using End Using End Using End SubThe result.
Best regards,
Ackerly Xu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, April 2, 2019 5:56 AM -
User-893317190 posted
Hi alihusain_77,
In fact, I haven't written my code according to your code, so there are many differences between your code and mine.
It is easier to refer to my code to rewrite your code instead of modifying your original code.
For example , your insert query is INSERT INTO PostingsTags(RefNo,KeyTag) VALUES(@RNo,@Tag) which inserts one record at a time.
But mine inserts all the newly created tags at a time , so my query is INSERT INTO PostingsTags(RefNo,KeyTag) VALUES(@RNo,@Tag),(@RNO,@Tag2),(@RNO,@Tag3).
Your delete query is DELETE FROM PostingsTags WHERE (RefNo=@RNo). Mine is DELETE FROM PostingsTags WHERE (RefNo=@RNo) and KeyTag in (@tag1,@tag2,@tag3) which deletes all the tags the user want to delete.
I use Public tags As List(Of String) = New List(Of String) to stores all the tags and use
<% For Each tag In tags %> <li> <%=tag %></li> <% Next %>
to render the tags in aspx.
And your data is stored in a string using comma as delimiter.
I also use
var tagArr = []; $.each($("input[name=tags]"), function (index, ele) { tagArr.push(ele.value); }) $("#<%= HiddenField1.ClientID%>").val(tagArr.join(","))
to store original data of the tags to compare with newly created tags to know what to insert and what to delete.
Below is the logic what I use to get what to insert and what to delete.
Dim newTags = Request.Form("tags").Split(","c) ' get all the newTags Dim oldTags = HiddenField1.Value.Split(","c) ' get original oldTages Dim valuesToDelete = oldTags.Except(newTags).Distinct().ToList() ' get values to delete ' Except will get all the values which is in oldTags and is not in newTags Dim valuesToInsert = newTags.Except(oldTags).Distinct().ToList() ' get values to insert
Since there are these differences in your code and my code , you had better not modify your code.
If you must modify your code , please refer to the differences I have shown.
If you have problem understanding my code , please let me know.
Best regards,
Ackerly Xu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, April 3, 2019 1:33 AM
All replies
-
User-943250815 posted
Use ListView and set its datasource on code behind to populate on Page Load.
Then adjust LI content and Jquery to your needs<asp:ListView ID="ListView2" runat="server" EnableViewState="false"> <LayoutTemplate> <ul> <li id="itemPlaceholder" runat="server"></li> </ul> </LayoutTemplate> <ItemTemplate> <li id='<%# String.Format("#code{0}", Container.DataItem) %>'><%# Container.DataItem %></li> </ItemTemplate> </asp:ListView>
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load ListView2.DataSource = GetDataList() ListView2.DataBind() End Sub
Public Shared Function GetDataList() As List(Of String)
Dim StoredTagsList As SqlDataReader
Dim data As New List(Of String) = Nothing
Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
Using connection As New SqlConnection(conString)
connection.Open()
Dim querystring As String = "SELECT DISTINCT KeyTag FROM PostingsTags"
Dim ExtractTagsList As New SqlCommand(querystring, connection)
StoredTagsList = ExtractTagsList.ExecuteReader()
If StoredTagsList.HasRows Then
Do While StoredTagsList.Read()
If StoredTagsList(0) <> "" Then
data.Add(StoredTagsList(0))
End If
Loop
End If
End Using
Return data
End FunctionMonday, April 1, 2019 7:54 PM -
User-893317190 posted
Hi alihusain_77 ,
It seems you are using jqueryui plugin tags.
You could use a list which stores values at code behind and render the list as ul at aspx.
Because you want to combine insert and delete function in the ul , I suggest you could record original data in a hidden field.
When the user click submit , get the submitted data to compare with original data so that you could know what to delete and what to insert.
Below is my code.
<head runat="server"> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script> <script src="../Scripts/tag-it.js"></script> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css" /> <link href="../Content/jquery.tagit.css" rel="stylesheet" /> </head> <body> <form id="form1" runat="server"> <ul id="myTags">
<!--render the data--> <% For Each tag In tags %> <li> <%=tag %></li> <% Next %> </ul> <asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" /> <asp:HiddenField ID="HiddenField1" runat="server" /> <script type="text/javascript"> $(document).ready(function() { $("#myTags").tagit(); // store the original data and assign the original data to a hidden field
// all the original data is stored in input whose name is tags var tagArr = []; $.each($("input[name=tags]"), function (index, ele) { tagArr.push(ele.value); }) $("#<%= HiddenField1.ClientID%>").val(tagArr.join(",")) }); </script> </form> </body>Code behind.
Inherits System.Web.UI.Page Private constr As String = ConfigurationManager.ConnectionStrings("EntityDb").ConnectionString Public tags As List(Of String) = New List(Of String) Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then Using con As SqlConnection = New SqlConnection(constr) ' select all the keytag from database and save value in tags Using com As SqlCommand = New SqlCommand("select keytag from postingsTags where Refno=@no ", con) con.Open() com.Parameters.AddWithValue("no", "id1") 'please change your id1 to your sessionvalue Using reader As SqlDataReader = com.ExecuteReader() If reader.HasRows Then While reader.Read() tags.Add(reader.GetString(0)) End While End If End Using End Using End Using End If End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Dim newTags = Request.Form("tags").Split(","c) ' get all the newTags Dim oldTags = HiddenField1.Value.Split(","c) ' get original oldTages Dim valuesToDelete = oldTags.Except(newTags).Distinct().ToList() ' get values to delete
' Except will get all the values which is in oldTags and is not in newTags Dim valuesToInsert = newTags.Except(oldTags).Distinct().ToList() ' get values to insert ' Except will get all the values which is in newTags and is not in oldTags
If valuesToDelete.Count > 0 Then Dim deleteSql = "delete from postingstags where keyTag in (" 'splice string to get the final deleteSql Using con As SqlConnection = New SqlConnection(constr) Using com As SqlCommand = New SqlCommand("", con)
'loop through valuesToDelete For index = 0 To valuesToDelete.Count - 1 If index = 0 Then
'add every delete parameter to sql deleteSql += "@parameter" & index ' Else deleteSql += ",@parameter" & index End If
' add value to every delete parameter com.Parameters.AddWithValue("parameter" & index, valuesToDelete(index)) Next deleteSql += ")" com.CommandText = deleteSql con.Open() Response.Write("you have deleted " & com.ExecuteNonQuery().ToString() & " record") End Using End Using End If If valuesToInsert.Count > 0 Then Dim insertSql = "insert into postingstags (RefNo,KeyTag) values " Using con As SqlConnection = New SqlConnection(constr) Using com As SqlCommand = New SqlCommand("", con)
'loop through every insert parameter For index = 0 To valuesToInsert.Count - 1
'add every insert parameter to sql If index = 0 Then insertSql += "(@RefNo,@parameter" & index.ToString() & ")" Else insertSql += ",(@RefNo,@parameter" & index.ToString() & ")" End If
'assign value to every insert parameter com.Parameters.AddWithValue("parameter" & index, valuesToInsert(index)) Next com.Parameters.AddWithValue("RefNo", "id1") com.CommandText = insertSql con.Open() Response.Write("<br/>you have inserted " & com.ExecuteNonQuery().ToString() & " record") End Using End Using End If ' reselect Using con As SqlConnection = New SqlConnection(constr) Using com As SqlCommand = New SqlCommand("select keytag from postingsTags where Refno=@no ", con) con.Open() com.Parameters.AddWithValue("no", "id1") Using reader As SqlDataReader = com.ExecuteReader() If reader.HasRows Then While reader.Read() tags.Add(reader.GetString(0)) End While End If End Using End Using End Using End SubThe result.
Best regards,
Ackerly Xu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, April 2, 2019 5:56 AM -
User-786564416 posted
Thanks a lot Ackerly for this help. However, Would you please show me how my content page that shown in the beginning will be after making the changes you have been suggested?
I will highly appreciate your help.
Tuesday, April 2, 2019 8:48 PM -
User-893317190 posted
Hi alihusain_77,
In fact, I haven't written my code according to your code, so there are many differences between your code and mine.
It is easier to refer to my code to rewrite your code instead of modifying your original code.
For example , your insert query is INSERT INTO PostingsTags(RefNo,KeyTag) VALUES(@RNo,@Tag) which inserts one record at a time.
But mine inserts all the newly created tags at a time , so my query is INSERT INTO PostingsTags(RefNo,KeyTag) VALUES(@RNo,@Tag),(@RNO,@Tag2),(@RNO,@Tag3).
Your delete query is DELETE FROM PostingsTags WHERE (RefNo=@RNo). Mine is DELETE FROM PostingsTags WHERE (RefNo=@RNo) and KeyTag in (@tag1,@tag2,@tag3) which deletes all the tags the user want to delete.
I use Public tags As List(Of String) = New List(Of String) to stores all the tags and use
<% For Each tag In tags %> <li> <%=tag %></li> <% Next %>
to render the tags in aspx.
And your data is stored in a string using comma as delimiter.
I also use
var tagArr = []; $.each($("input[name=tags]"), function (index, ele) { tagArr.push(ele.value); }) $("#<%= HiddenField1.ClientID%>").val(tagArr.join(","))
to store original data of the tags to compare with newly created tags to know what to insert and what to delete.
Below is the logic what I use to get what to insert and what to delete.
Dim newTags = Request.Form("tags").Split(","c) ' get all the newTags Dim oldTags = HiddenField1.Value.Split(","c) ' get original oldTages Dim valuesToDelete = oldTags.Except(newTags).Distinct().ToList() ' get values to delete ' Except will get all the values which is in oldTags and is not in newTags Dim valuesToInsert = newTags.Except(oldTags).Distinct().ToList() ' get values to insert
Since there are these differences in your code and my code , you had better not modify your code.
If you must modify your code , please refer to the differences I have shown.
If you have problem understanding my code , please let me know.
Best regards,
Ackerly Xu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, April 3, 2019 1:33 AM -
User-786564416 posted
Thanks Mr. Ackerly. I solved most of the problem except that, whenever the page opened, when the user start typing, the list of all distinct tags that was populated by the GetDataList function through the following, is no longer shown. So what is the replacement of this function in the new code you show, so the user see all the list of the keytags available that he can use whenever he start typing?
'get the data list, used to populate the autocomplete available tags. Public Shared Function GetDataList() As String Dim StoredTagsList As SqlDataReader Dim datalist As String Dim data As List(Of String) = New List(Of String)() Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString Using connection As New SqlConnection(conString) connection.Open() querystring = "SELECT DISTINCT KeyTag FROM PostingsTags" Dim ExtractTagsList As New SqlCommand(querystring, connection) StoredTagsList = ExtractTagsList.ExecuteReader() If StoredTagsList.HasRows Then Do While StoredTagsList.Read() If StoredTagsList(0) <> "" Then data.Add(StoredTagsList(0)) End If Loop End If End Using datalist = String.Join(",", data) Return datalist End Function
My new aspx code is:
<%@ Page Title="" Language="VB" ClientIDMode="Static" MasterPageFile="~/MasterPages/MyMasterPage.master" AutoEventWireup="false" CodeFile="Tag.aspx.vb" Inherits="NewPosting_Tag" MaintainScrollPositionOnPostback="true" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> <style type="text/css"> .MainFieldsDivStyle { border-color: Black; width: 70%; border-style: solid; margin-top: 22px; background-color:#C9DCF2; /*opacity: 0.8;*/ -moz-border-radius: 15px; -webkit-border-radius: 15px; border-radius: 15px; } .auto-style1 { height: 37px; } </style> <link rel="stylesheet" type="text/css" href="<%= ResolveUrl("~/jquery/js/jquery-ui.css")%>"/> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css" /> <link rel="stylesheet" type="text/css" href="<%= ResolveUrl("~/jquery/js/jquery.tagit.css")%>"/> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="CpMainContent" Runat="Server"> <asp:toolkitscriptmanager ID="ScriptManager1" runat="server" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script> <script src="<%=ResolveUrl("~/jquery/js/tag-it.js") %>" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $("#myTags").tagit(); // store the original data and assign the original data to a hidden field // all the original data is stored in input whose name is tags var tagArr = []; $.each($("input[name=tags]"), function (index, ele) { tagArr.push(ele.value); }) $("#<%= HiddenField1.ClientID%>").val(tagArr.join(",")) }); </script> <div id="MainDiv" class="MainFieldsDivStyle"> <ul id="myTags"> <!--render the data--> <% For Each tag In tags %> <li> <%=tag %></li> <% Next %> </ul> <asp:Button ID="btnSubmit" runat="server" Text="submit" OnClick="btnSubmit_Click" /> <asp:HiddenField ID="HiddenField1" runat="server" /> </div> </asp:Content>
The code-behind:
Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Imports System.Diagnostics Imports System.Net Imports System.Net.Mail Imports System.Web Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.Services Imports System.Text Imports System.String Partial Class NewPosting_Tag Inherits System.Web.UI.Page Public Shared querystring As String Public Shared EnteredTags As String Public Shared UserName As String Public Shared tags As List(Of String) = New List(Of String) Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click 'lblOutput.Text = hidSelectedValue.Value EnteredTags = HiddenField1.Value If Len(EnteredTags) > 0 Then ' you want to split this input string Dim s As String = EnteredTags ' Split string based on comma Dim words As String() = s.Split(New Char() {","c}) ' Use For Each loop over words and display them Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString Using connection As New SqlConnection(conString) connection.Open() querystring = "DELETE FROM PostingsTags WHERE (RefNo=@RNo)" Dim ClearOldRecords As New SqlCommand(querystring, connection) ClearOldRecords.Parameters.Add("@RNo", SqlDbType.NVarChar) ClearOldRecords.Parameters("@RNo").Value = Session("TagsRefNo") ClearOldRecords.ExecuteNonQuery() End Using Dim word As String For Each word In words AddNewTag(word) Next ScriptManager.RegisterStartupScript(Page, GetType(Page), "CloseWindow", "window.close();", True) End If End Sub 'get the data list, used to populate the autocomplete available tags. Public Shared Function GetDataList() As String Dim StoredTagsList As SqlDataReader Dim datalist As String Dim data As List(Of String) = New List(Of String)() 'data.Add("Ebrahim") Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString Using connection As New SqlConnection(conString) connection.Open() querystring = "SELECT DISTINCT KeyTag FROM PostingsTags" Dim ExtractTagsList As New SqlCommand(querystring, connection) StoredTagsList = ExtractTagsList.ExecuteReader() If StoredTagsList.HasRows Then Do While StoredTagsList.Read() If StoredTagsList(0) <> "" Then data.Add(StoredTagsList(0)) End If Loop End If End Using datalist = String.Join(",", data) Return datalist End Function Public Sub AddNewTag(ByVal Tag As String) Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString Using connection As New SqlConnection(conString) connection.Open() querystring = "INSERT INTO PostingsTags(RefNo,KeyTag) VALUES(@RNo,@Tag)" Dim InsertNewTag As New SqlCommand(querystring, connection) InsertNewTag.Parameters.Add("@RNo", SqlDbType.NVarChar) InsertNewTag.Parameters("@RNo").Value = Session("TagsRefNo") InsertNewTag.Parameters.Add("@Tag", SqlDbType.NVarChar) InsertNewTag.Parameters("@Tag").Value = Tag InsertNewTag.ExecuteNonQuery() End Using End Sub Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Session("UserName") = "" Then Response.Redirect("~\Logon\LogonScreen.aspx") End If UserName = Session("username") Dim RefNoKeyTags As SqlDataReader Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString Using connection As New SqlConnection(conString) connection.Open() querystring = "SELECT DISTINCT KeyTag FROM PostingsTags WHERE (RefNo=@RNo)" Dim LoadRefNoKeyTags As New SqlCommand(querystring, connection) LoadRefNoKeyTags.Parameters.Add("@RNo", SqlDbType.NVarChar) LoadRefNoKeyTags.Parameters("@RNo").Value = Session("TagsRefNo") RefNoKeyTags = LoadRefNoKeyTags.ExecuteReader() If RefNoKeyTags.HasRows Then While RefNoKeyTags.Read() tags.Add(RefNoKeyTags(0)) End While RefNoKeyTags.Close() End If End Using End Sub End Class
So why I can't see the list of all tags that were generated by the query: "SELECT DISTINCT KeyTag FROM PostingsTags" when start typing?
Wednesday, April 3, 2019 11:26 AM -
User-786564416 posted
You had very much helped me solving the tags problem. However, I am now having in the same issue another critical problem explained in this post: https://forums.asp.net/t/2154433.aspx?How+to+refer+to+the+entered+tags+to+get+it+
Wednesday, April 3, 2019 3:56 PM -
User-893317190 posted
Hi alihusain_77 ,
Not sure about your requirement, if you want to get all the entered tags, you could
Form client side.
<ul id="myTags"> <!-- Existing list items will be pre-added to the tags --> <% For Each tag In tags %> <li> <%=tag %></li> <% Next %> </ul> <asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" /> <asp:HiddenField ID="HiddenField1" runat="server" /> <input type="button" onclick="showValues()" value="click"/> <script type="text/javascript"> function showValues() { var values = []; $.each($("input[name=tags]"), function (index, ele) { values.push(ele.value); }) alert(values); } $(document).ready(function() { $("#myTags").tagit(); var tagArr = []; $.each($("input[name=tags]"), function (index, ele) { tagArr.push(ele.value); }) $("#<%= HiddenField1.ClientID%>").val(tagArr.join(",")) }); </script>
The result.
If you want to get it in code behind, you could use
Dim newTags = Request.Form("tags").Split(","c)
Best regards,
Ackerly Xu
Monday, April 8, 2019 1:57 AM