How to make jquery autocomplete works from usercontrol using webservice - c#

I have jQuery to pull the autocomplete record as I type in the textbox, this data is being fetched using webservice. Now, everything works fine while using in Default.aspx page, but when I use this process from UserControl.ascx and call it in the default.aspx page then it doesn't return the autocomplete data (result).
WebService.asmx code:
[WebMethod]
public List<string> GetAutoCompleteData(string username)
{
string conString = ConfigurationManager.ConnectionStrings["MYCONNECTION"].ConnectionString;
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT SSName from SSRecord where SSName LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["SSName "].ToString());
}
return result;
}
}
}
UserControl.ascx code:
<script src="jquery-1.11.2.js" type="text/javascript"></script>
<link href="jquery-ui.css" rel="stylesheet" />
<script src="jquery-ui.js" type="text/javascript"></script>
<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: "WebService.asmx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
<label for="tbAuto">Enter UserName: </label>
<asp:TextBox ID="txtSearch" runat="server" class="autosuggest"></asp:TextBox>
Default.aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Src="~/UserControl.ascx" TagPrefix="uc1" TagName="UserControl" %>
<body>
<form id="form1" runat="server">
<div>
<uc1: UserControl runat="server" ID="UserControl"/>
</div>
</form>
</body>

I got the similar post on the below link. Therefore, after some modification mentioned in the link I am able to sort this out.
https://www.aspsnippets.com/Articles/Implement-jQuery-Autocomplete-using-Web-Service-in-ASP.Net.aspx

Related

can not get data form function using ajax jquery in asp.net c#

i am trying use $.ajax() method in asp.net to fill a html tag but i didn't get any data from on success parameter
i am calling getData function from c# code and I tried to return a string but it doesn't work i also tried to user Response.write() but the same issue
when I alert returned value it show me the aspx page code
as following image
here is my code
Default.apsx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#firstDrop").on("change", function () {
$.ajax({
url: "Default.aspx/getData",
type: "POST",
data: { id: $("#firstDrop").val() },
success: function (data) {
alert(data);
$("#secondDrop").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select runat="server" id="firstDrop">
<option value="0">first select</option><option value="1">second select</option><option value="3">third select</option>
</select>
<select id="secondDrop"></select>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string getData()
{
return"<option>ABC</option><option>CDE</option>";
}
}
Basic rule when creating a webmethod in asp.net.
Your method should be static.
You need to decorate your function with System.Web.Services.WebMethod.
C# Code Behind
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Javascript (Aspx)
Here, in your case make your getdata function static and webmethod as well. When calling the webmethod through ajax use data.d to read the response.
[System.Web.Services.WebMethod]
public static string getData(int id)
{
return "<option>ABC</option><option>CDE</option>";
}
$("#firstDrop").on("change", function() {
$.ajax({
url: "Default.aspx/getData",
type: "POST",
dataType: "json",
data: {
id: $("#firstDrop").val()
},
success: function(data) {
alert(data.d);
$("#secondDrop").html(data.d);
}
});
});
Reference Site:
https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Similar thread "Calling webmethod in webform"
calling-a-webmethod-with-jquery-in-asp-net-webforms

Unable to return typehead.js with asp.net and ajax

I am trying to return my query as a user enters in information. However when I enter data into the textbox it returns an HTML popup page with random HTML code. I can figure out why the ajax callback isn't finding the [webmethod] as I think this may be the issue.
Default.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>testing typescript</title>
<link rel="stylesheet" href='http://cdnjs.cloudflare.com/ajax/libs/twitter- bootstrap/3.0.3/css/bootstrap.min.css'
media="screen" />
<script type="text/javascript" src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
<script type="text/javascript" src="http://cdn.rawgit.com/bassjobsen/Bootstrap-3-Typeahead/master/bootstrap3-typeahead.min.js"></script>
<link rel="Stylesheet" href="https://twitter.github.io/typeahead.js/css/examples.css" />
<script type="text/javascript">
$(function () {
$('[id*=txtSearch]').typeahead({
hint: true,
highlight: true,
minLength: 1
, source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("/Default.aspx.cs/GetCustomers") %>',
data: "{ 'prefix': '" + request + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
items = [];
map = {};
$.each(data.d, function (i, item) {
var id = item.split('-')[1];
var name = item.split('-')[0];
map[name] = { id: id, name: name };
items.push(name);
});
response(items);
$(".dropdown-menu").css("height", "auto");
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
updater: function (item) {
$('[id*=hfCustomerId]').val(map[item].id);
return item;
}
});
});
</script>
</head>
<body>
Enter search term:
<form runat="server">
<asp:TextBox ID="txtSearch" runat="server" CssClass="form-control" autocomplete="off"
Width="300"/>
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
</form>
</body>
</html>
Default.aspx.cs (code behind file)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit(object sender, EventArgs e)
{
string customerName = Request.Form[txtSearch.UniqueID];
string customerId = Request.Form[hfCustomerId.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + customerName + "\\nID: " + customerId + "');", true);
}
[WebMethod]
public static string[] GetCustomers(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "<%$ ConnectionStrings:FormDataConnectionString %>";
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT [ID], [name], FROM [Wireless_Order] where ContactName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["name"], sdr["ID"]));
}
}
conn.Close();
}
}
return customers.ToArray();
}
}
I have included this in my web.config file
<system.web>
<pages clientIDMode="Static"></pages>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
The issue was here.
/Default.aspx.cs/GetCustomers
Needed to be
Default.aspx/GetCustomers
to find the file.
Still get an error though when I click the backspace to clear the textfield.

jQuery autocomplete selection with mouse click doesn't get selected. the textbox still post back with typed value not selected value in IE

jQuery autocomplete selection with mouse click doesn't get selected in IE. The textbox (that is inside GridView, EditItemTamplate) still post back with the typed in text box not the selected value from dropdown list in IE. It works fine in Google and Firefox.
This code is in my content page. When I type a letter in the texbox, autocomplete give me a list of options. If I use 'up' or 'down' arrow and select the option, it populate my textbox correctly. But if I choose an option with a mouse click, then it doesn't populate my textbox with the option I chose, it just posts back with whatever I typed in the textbox.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="BlindKeyVerification.aspx.cs" Inherits="Test.Administration.BlindKeyVerification" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link href="../Styles/jquery-ui.css" rel="stylesheet" />
<link href="../Styles/jquery-ui.min.css" rel="stylesheet" />
<script src="../Scripts/jquery.js" type="text/javascript"></script>
<script src="../Scripts/jquery-ui.js" type="text/javascript"></script>
<script src="../Scripts/jquery-ui.min.js" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$("[id*=txtGridCode]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("/Administration/priceCodeService.asmx/getPriceCodeArray") %>',
data: "{ 'priceCode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item,
val: item.split('-')[0]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
$("[id*=txtGridCode]").autocomplete({
select: function (event, ui) {
$this = $(this);
setTimeout(function () {
$("[id*=txtGridCode]").val(ui.item.val);
}, 1);
}
});
});
function InitializeRequest(sender, args) {
$("*").css("cursor", "wait");
}
function EndRequest(sender, args) {
$("*").css('cursor', 'auto');
}
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
//if ((evt.keyCode == 13) && (node.type == "text")) { return false; } //Stop return Key from Posting the page
if ((evt.keyCode == 8) && (node.type == "select-one")) { return false; } //dropdown box backspace stop backpage
}
document.onkeypress = stopRKey; //Firefox
document.onkeydown = stopRKey; //i.e.
</script>
Some parts of the textbox inside the GridView:
BlinkKeyVerfication.aspx
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lblCode" runat="server" ForeColor="Red" Font-Size="Smaller">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGridCode" runat="server" OnTextChanged="txtGridCode_TextChanged" AutoPostBack="true"></asp:TextBox>
</EditItemTemplate>
<ItemStyle Font-Size="Smaller" />
</asp:TemplateField>
</Columns>
</asp:GridView>
priceCodeService.asmx.cs
public partial class WebForm1 : System.Web.UI.Page
{
public List<string> getPriceCodeArray(string priceCode)
{
List<string> doc = new List<string>();
string CSConn = "Server=CourtData;Initial Catalog= CourtSupport; Integrated Security = SSPI";
using (SqlConnection conn = new SqlConnection(CSConn))
{
using (SqlCommand comm = new SqlCommand("SELECT priceCode, priceText FROM tblpriceCodeExtract WHERE priceCode like #priceCode + '%'", conn))
{
SqlParameter parameter_code = new SqlParameter();
parameter_code.ParameterName = "#priceCode";
parameter_code.Value = priceCode;
comm.Parameters.Add(parameter_code);
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
while (rdr.Read())
{
//string doccode = rdr["priceCode"].ToString();
//string codetext = rdr["priceText"].ToString();
//if (codetext.Length > 30)
// codetext = codetext.Substring(0, 29) + "...";
//doc.Add(string.Format("{0}-{1}", doccode, codetext));
doc.Add(rdr["priceCode"].ToString());
}
}
}
return doc;
}
}
Because of compatibility view, my code was not working properly, our site is in compatibility view.
In my aspx content page head section I had following code, but it don't had any use because my masterpage code was blocking it
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
then i removed that code from content page and I added following code in my .cs file
protected void Page_Load(object sender, EventArgs e)
{
if (Header.Controls[1].GetType() != typeof(System.Web.UI.HtmlControls.HtmlMeta))
{
System.Web.UI.HtmlControls.HtmlMeta meta = new System.Web.UI.HtmlControls.HtmlMeta();
meta.HttpEquiv = "X-UA-Compatible";
meta.Content = "IE=edge";
this.Header.Controls.AddAt(1, meta);
}
Now my code is working fine in all browser. Now I don't need any more select event in my code. so i removed it.

Call asp.net function from javascript function

I want to call asp.net function from a javascript function passing string value.
this is the asp.net function :
[System.Web.Services.WebMethod]
public static string InsertData(string ID)
{
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
using(SqlConnection con = new SqlConnection(source))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con)) {
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
return "True";
}
}
}
So i want to call this function from javascript function which passes the string value "ID" to the the asp.net function.
this is the javascript function i use
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Errorrr');
}
and i call it from here
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
so i have a button and onClick i want to add "Hello" Row to my table but nothing happens and CallError function calls
You can call web method from ajax call in javascript . you need to set url parameter values to function you want to call and you can pass value in the data prameter in json formate.
like this data:"{ParamterName:'VALUE'}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/YouPageMethod",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Method Called Sucess fully');
},
error: function (result) {
alert("error " + result);
}
});
});
</script>
OR
you can call using PageMethod Eample
<script type="text/javascript">
function callInsert() {
PageMethods.InsertDate(id, OnSucceeded, OnFailed);
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
/* call this javascript function */
callInsert();
</script>
You will need to include Jquery first in your page. Then you need to add the following Javascript code.
<script type="text/javascript">
var id ="5"; //your id will be stored here
$(document).ready(function () {
$.ajax({
type: "POST",
url: "YourPage.aspx/InsertData" + "&?id=" ,
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Success');
},
error: function (xhr, request, status) {
alert(xhr.responseText);
}
});
});
</script>
You need to have scriptManager in your .aspx page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
After that you can call the method using
<script type="text/javascript">
function func(){
PageMethods.InsertData(id,success_msg,failure_msg);
}
</script>

AutoComplete for Asp.net C# Not working?

I have tried everything. I am trying to get autocomplete to work for an input textbox and I can't get it to work. I am implementing it into a DNN webpage here is the code I am using for this autocomplete...
I keep getting error every time.
I am welcome to do a teamviewer session.
Thank you.
ASP.NET code
<asp:Panel ID="pnlInfoSearch" runat="server">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<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: "View.ascx/GetPartNumber",
data: "{'PartNumber':'" + document.getElementById('txtPartNum').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
<div id="introcopy">
<h2>Product Info Center</h2>
<p>Download technical and quality documents, check inventory and order samples for your parts.</p>
</div>
<div class="demo">
<p>Enter a part number (or portion of a part number) to retrieve information about that product.</p>
<input type="text" id="txtPartNum" value="Enter part #..." style="height: 18px" class="autosuggest" />
</div>
<script type="text/javascript">
// <![CDATA[
var _sDefaultText = 'Enter part #...';
jQuery('#txtPartNum').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
window.location.href = '<%= new Uri(String.Concat("http://", Page.Request.UserHostName, Page.Request.RawUrl)).AbsolutePath %>?partnum=' + jQuery(this).val();
}
}).focus(function () {
if (jQuery(this).val() === _sDefaultText) {
jQuery(this).val('');
}
}).blur(function () {
if (jQuery(this).val().length == 0) {
jQuery(this).val(_sDefaultText);
}
});
// ]]>
</script>
<br class="clear" />
</asp:Panel>
C# code....
[WebMethod]
public static List<string> GetPartNumber(string PartNumber)
{
List<string> result = new List<string>();
using (SqlConnection conn = new SqlConnection("HIDDEN"))
{
using (SqlCommand cmd = new SqlCommand("select PartNumber from Products.Products where PartNumber LIKE #SearchText+'%'", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#SearchText", PartNumber);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["PartNumber"].ToString());
}
return result;
}
}
}
If you think your issue is SQL related, then refactor the SQL related code and write some tests against that method with some know part numbers.
Looking at your code, the URL for your service method stands out. You specify You specified url: "View.ascx/GetPartNumber" but I would assume you either meant something else (maybe View.ashx or View.asmx). Are you able to hit your service method via your browser as a simple GET?
What do you get when you access this URI in your browser? /View.ascx/GetPartNumber?PartNumber=xyz

Categories

Resources