I want to create a tagging system for my website which allows user to enter the required skills,separated by comma, using ASP.net and C#.
In detail:
A textbox will receive tags, separated by comma.
Suggestions will be provided while typing, based on AVAILABLE tags in my database.
Suggested tags will be displayed, below the textbox.
If a new tag is encountered, it is inserted into database.
The tags (separated by comma), given by the user could be further manipulated according to my needs (a way of doing that).
I want to make a separate entry for each and every tag into the database.
I tried using Tag-it by Levy Carneiro Jr.. it is working perfect for local source.
But when I tried attaching it with my database using this. It just doesn't work.
My code:-
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "tag.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('singleFieldTags2').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
<script>
$(function () {
//Local sample- //var sampleTags = ['c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python', 'c', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
$('#singleFieldTags2').tagit({
});
});
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox name="tags" id="singleFieldTags2" value="Apple, Orange" class="autosuggest" runat="server"></asp:TextBox>
</form>
Backend C# code-
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=ZESTER-PC;Initial Catalog=mystp;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select tag_name from tags where tag_name LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["tag_name"].ToString());
}
return result;
}
}
}
Here tags is my tag table containing tag_id and tag_name.
I have created the Tagging System using ASP.net
Check it out.. nd do rate it..
Tagging System using ASP.net by Sumanyu Soniwal
Related
I am trying to pass data through jquery ajax but facing issue. I am getting data in the json format
data:'{user: ' + JSON.stringify(user)+'}'
like this
user = {Tdcno: "tw5", Revision: "0", Revision_Date: "22/11/2017", P_Group: "Chain Link", Prod_Desc: "GI wire for chain link", …}
but after processing at this step it directly goes to failure.Any help would appreciated for resolving.
<script type="text/javascript">
$(function () {
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var user = {};
user.Tdcno = $("[id*=Tdc_No]").val();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
c# code
[WebMethod]
[ScriptMethod]
public void SaveFrmDetails(User user)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TDC_PRODUCT1 VALUES(#Tdc_No, #Revision,#Revision_Date,#P_Group,#Prod_Desc,#N_I_Prd_Std,#Appln,#Frm_Supp,#Created_Date,#Created_By)"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Never manually create json strings. It is error prone and more work than serializing them with JSON.stringify.
'{user: ' + JSON.stringify(user) + '}' produces invalid json because the property user is not properly quoted
Stringify the whole data object
data: JSON.stringify({user:user}})
I am trying to pass HiddenField value to WebMethod GetAutoCompleteData to enable auto complete in text box based on selected search field.
I have tried pass HiddenField values using code-behind, but it didn't work.
There is no issues with javascript codes.
Note: I have tried to use HiddenField value in another method, and it worked, so I am sure that HiddenField is taking values using JavaScript code.
Code-behind:
public static string hdnvalue { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
hdnvalue = hdnSearchParam.Value;
}
[WebMethod]
public static List<string> GetAutoCompleteData(string value)
{
string hiddenfiedlvalue = hdnvalue;
List<string> result = new List<string>();
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("select #hiddenfiedlvalue from Users where #hiddenfiedlvalue LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", value);
cmd.Parameters.AddWithValue("#hiddenfiedlvalue", hiddenfiedlvalue);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(string.Format("{0}", hiddenfiedlvalue));
}
return result;
}
}
}
Code used to pass selected values from drop-down menu to HiddenField:
<script type="text/javascript">
$(document).ready(function (e) {
$('.search-panel .dropdown-menu').find('a').click(function (e) {
e.preventDefault();
var param = $(this).attr("href").replace("#", "");
var concept = $(this).text();
$('.search-panel span#search_concept').text(concept);
$('[id$=hdnSearchParam]').val(param);
});
});
</script>
Auto complete code:
<script type="text/javascript">
$(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'value':'" + $('#txtSearch').val() + "'}",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
}
else {
response([{ label: 'No Records Found', val: -1 }]);
}
},
error: function (result) {
alert("Error");
}
});
},
});
}
</script>
ASPX:
<asp:HiddenField ID="hdnSearchParam" runat="server" />
<div class="col-xs-8">
<div class="input-group">
<div class="input-group-btn search-panel">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span id="search_concept">Filter by</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>User ID</li>
<li>User Type</li>
<li>User Name</li>
<li>First Name</li>
<li>Last Name</li>
<li>Email</li>
</ul>
</div>
<input type="hidden" name="search_param" value="all" id="search_param">
<asp:TextBox ID="txtSearch" CssClass="autosuggest form-control" runat="server"></asp:TextBox>
<span class="input-group-btn"></span>
</div>
</div>
Your page has several issues.
First, why are you using a hidden field for this? Why don't you just pass the dropdown value as a second parameter in the Ajax request?
Second, in your code behind you are reading the hidden value only on page load, and that value is never updated with each Ajax request (Page_Load is not executed again). You made that static trick with hdnvalue just to make it compile, but it won't work. Also, making it static makes it be shared among all web clients using that page!
Third, why are you storing the dropdown value in its href as well? You could use a span or even simple text instead.
Fourth, you are using the server controls markup ID instead of the ClientID, which may be different depending on the .NET framework you are using. Better play safe and use ClientID always.
Fifth, if with jQuery you select by ID, just use the ID, there's no need to use any other class selectors. Of course, you should never have repeated IDs!
Sixth, you can't use parameterized variables as column names. You must use a dynamic query. More info about that here. Also the reader wasn't working properly (only adding the hidden field) and it's better to enclose the ExecuteReader in a using block.
Summarizing, use this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string value, string filterBy)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
con.Open();
string command = string.Format("select {0} from Users where {0} LIKE '%'+#SearchText+'%'", filterBy);
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("#SearchText", value);
using (SqlDataReader dr = cmd.ExecuteReader())
{
List<string> result = new List<string>();
while (dr.Read())
{
result.Add(dr.GetString(0));
}
return result;
}
}
}
}
<script type="text/javascript">
$(document).ready(function (e) {
$('.search-panel .dropdown-menu').find('a').click(function (e) {
e.preventDefault();
var concept = $(this).text();
$('#search_concept').text(concept);
});
});
</script>
Important: if you are afraid of SQL Injection, you may want to do some validation with filterBy first.
In your Javascript, fix this line only:
data: "{'value':'" + $('#<%= txtSearch.ClientID %>').val() + "','filterBy':'" + $('#search_concept').text() + "'}",
Finally, just get rid of both hidden fields (user control and html control).
try to change data parameter to this:
data: "{'value':'" + $('#hdnSearchParam').val() + "'}",
Try removing the dollar sign from this line of code.
$('[id$=hdnSearchParam]').val(param);
It should be smthing like this:
$('[ID="hdnSearchParam"]').val(param);
When I run this code I get alert saying Error.
My Code:
<script type="text/javascript">
debugger;
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'fname':'" + document.getElementById('txtCategory').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select fname from tblreg where fname LIKE '%'+#CategoryText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#CategoryText", CategoryName);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["fname"].ToString());
}
return result;
}
}
}
I want to debug my function GetAutoCompleteData but breakpoint is not fired at all.
What's wrong in this code? Please guide.
I have attached screen shot above.
You need to change the data property's value of you $.ajax() call to correctly reflect the C# method parameter i.e. change this line
data: "{'fname':'" + document.getElementById('txtCategory').value + "'}",
to
data: "{'CategoryName':'" + document.getElementById('txtCategory').value + "'}",
The data property should match the parameter in the signature of the action method.
You need to add [WebMethod] attribute over your method. so your method will look like this
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
....
How to use web method link
Edit 1
In your jQuery where you have written url: "GetAutoCompleteData", you need to specify the class or page name and then method name.
You cann't directly call Method you need to use the class (.aspx page) and then method.
I've been all over Google, attempting one example after another for both AJAX and jQuery AutoComplete.
I've decided on using jQuery's script to render the autocomplete method on my page and I'm using a web service to collect data from my SQL Ce data base.
Here is the error message I receive from jquery and I'm pretty sure that it derives from my webs service... Marr is short for Marriott, the search term I begin to type..
{"Message":"#SearchText : Marr - Input string was not in a correct format.","StackTrace":" at System.Data.SqlServerCe.SqlCeCommand.FillParameterDataBindings(Boolean verifyValue)\r\n at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)\r\n at System.Data.SqlServerCe.SqlCeCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.SqlServerCe.SqlCeCommand.ExecuteReader()\r\n at GetClients.GetClientNames(String prefix) in c:\Users\CRH-DEV\Desktop\Dev Projects\HelpDesk\App_Code\GetClients.cs:line 42","ExceptionType":"System.FormatException"}
The error derives from line 42 of my webservice's .cs but I'm not quite sure what I'm looking at. I'm guessing the data is not correctly formatted.
The example I am using derives from this website...
Implement jQuery Autocomplete using Web Service in ASP.Net
Here is my complete webservice...
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Web.Script.Services;
using System.Data.SqlServerCe;
/// <summary>
/// Summary description for Service_CS
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class GetClients : System.Web.Services.WebService
{
public GetClients()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetClientNames(string prefix)
{
List<string> customers = new List<string>();
using (SqlCeConnection conn = new SqlCeConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlCeCommand cmd = new SqlCeCommand())
{
cmd.CommandText = "SELECT [Name], [ID] FROM [Current] WHERE " +
"[Name] LIKE #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlCeDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["Name"], sdr["ID"]));
}
}
conn.Close();
}
return customers.ToArray();
}
}
}
My aspx Page..(head)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jqueryui.css" rel = "Stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#<%=ClientSearch.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/GetClients.asmx/GetClientNames") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfClientID.ClientID %>").val(i.item.val);
},
minLength: 1
});
});
</script>
aspx (body)..
<h1>jQuery Autocomplete Lab</h1>
<asp:TextBox ID="ClientSearch" runat="server"></asp:TextBox>
<asp:HiddenField ID="hfClientID" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick = "Submit" />
If needing, I can post additional code but I think the issue is with my webservice.
I would highly appreciate any feedback on this issue. I think the webservices have been whats killing my on all of the examples I've tried.
Kind Regards,
-Cody
You need to return JSON from you Webservice
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(YourArray);
also change the return type of you webservice function to string
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetClientNames(string prefix)
{
//YOUR CODE
}
hey I want to use autocomplete jquery in asp.net on a control which is used on a default1.aspx page. My control is searchinput.ascx which is in Registration folder. My ploblem is I have written web method (getmylist) on code file of searchinput control. but that method is never called. can anyone help me
Jquery website
You can find wat you need there for a start.
Also, show your ajax call so that I can try helping on y it is not working.
Your approach of writting a web method and making a ajax call from the jquery auto complete should work out fine otherwise.
Its hard to help you without the code but some common causes could be:
You are not using ClientID value correctly - asp.net controls dont have the same id in the actual mark-up as they do in the designer
your web method has an error in it - you should press f12 to open your web developers toolbar and go to NET tab (in firefox at least) to see if a 500 error code or similar is being returned
Create a web method like the following:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetPatientFirstName(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
string connectionstring = CCMMUtility.GetCacheForWholeApplication();
conn.ConnectionString = connectionstring;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select distinct top(10) PatientFirstname from tblMessage where " +
"PatientFirstname like '%'+ #SearchText + '%' order by PatientFirstname";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}", sdr["PatientFirstname"]));
}
}
conn.Close();
}
return customers.ToArray();
}
}
here is the html code :
$(document).ready(function () {
$('[ID$=txtPatientFirstname]').live('keyup.autocomplete', function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Resources/WebService.asmx/GetPatientFirstName") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
},
minLength: 1
});
});
});
This is the working example ......hope this will solve your problem..