AutoComplete for Asp.net C# Not working? - c#

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

Related

How to make jquery autocomplete works from usercontrol using webservice

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

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>

How to get javascript values on code behind in c#

I need to get javascript values on code behind in c#.I know i can use hidden field but there is no server control on page for postback.Please tell me how can get vales in code behind.
Here is my code:
<html>
<head>
<title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: 'APPID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
FB.api('/me', function (me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('myJSString').value = me.name;
alert(document.getElementById('myJSString').value);
document.getElementById('Email').innerHTML = me.email;
document.getElementById('profileImg').src = uid;
// document.getElementById('ctl00_CPHDefault_tcTPS_TPProd_ctl01_tcProduction_TPNewT‌​itlesStatus_ChangedRowsIndicesHiddenField').value = uid;
// alert('yyy');
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div id="Result" class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login</div>
</div>
<div id="auth-loggedin" style="display: none">
Name: <b><span id="auth-displayname"></span></b>(logout)<br />
Email: <b><span id="Email"></span></b><br />
Profile Image: <img id="profileImg" />
<form runat="server">
<asp:HiddenField runat="server" id="myJSString" />
</form>
</div>
</div>
</body>
</html>
You can see there is no server control so how i can get NAME,UID variables in code behind.
Thanks
You can use a hiddenfield server control assign the values you need to it in javascript and assess it on server side. If you do not want post back then you can use jQuery ajax to send values.
Html
<asp:hiddenfield id="ValueHiddenField" runat="server"/>
Javascript
document.getElementById('ValueHiddenField').value = "yourValue";
Code behind
string yourValue = ValueHiddenField.Value;
Using jQuery ajax and web method to send values to code behind, you can find nice tutorial over here.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: {'yourParam': '123'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Code behind
[WebMethod]
public static void YourMethod(string yourParam)
{
//your code goes here
}
I would investigate the use of ASP.NET AJAX Page Methods, because they allow for script callable stand-alone web services that live in an .aspx page, like this:
Page Method in your code-behind file (call it default.aspx for discussion's sake):
[WebMethod]
public static string SaveData(string name, string uid)
{
// Logic here to do what you want with name and uid values (i.e. save to database, call another service, etc.)
}
jQuery call to default.aspx's SaveData method:
$.ajax({
type: "POST",
url: "default.aspx/SaveData",
data: "{'name':'John', 'uid':'ABC123'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Notes: ASP.NET AJAX Page Methods automatically encode their response to JSON so you will not see any JSON serialization in the code-behind or any serialization logic at all.
For more information about ASP.NET AJAX Page Methods check out Using jQuery to directly call ASP.NET AJAX page methods
You can use following method:
<script language="javascript" type="text/javascript">
function returnString() {
var val = 'sampleValue';
return val;
}
</script>
C# Code to get the return value of the above function:
ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", "<script language="javascript">var a=returnString();alert(a);</script>");
Or simply as Adil said, can use hidden field and assign value:
<asp:HiddenField ID="hField" Value="0" runat="server" />
<asp:Button ID="Button1" runat="server" OnClientClick="returnString();"
Text="Button" onclick="Button1_Click" />
script for assigning value:
<script language="javascript" type="text/javascript">
function returnString() {
debugger;
document.getElementById("hField").value = "sampleValue";
}
</script>

Populating AutoComplete from WebService

I have managed to get a JQuery autocomplete working in C#.net using a webservice.
Here is the asp code:
<div class="row">
<div class="span4">
<h3>
Manage Season</h3>
</div>
</div>
<div class="row">
<div class="span2">
<p>
<label class="control-label" for="TeamName">
Team Name:</label></p>
</div>
<div class="span3">
<asp:TextBox ID="TeamNameTextBox" runat="server" CssClass="searchinput"></asp:TextBox>
<asp:Button ID="AddTeamButton" CssClass="btn btn-primary" runat="server" Text="Add"
OnClick="AddTeamButton_Click" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".searchinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PredictiveSearch.asmx/GetAllPredictions",
data: "{'keywordStartsWith':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
},
minLength: 1
});
});
</script>
And the c# web service:
[System.Web.Script.Services.ScriptService]
public class PredictiveSearch : System.Web.Services.WebService
{
[WebMethod]
public IList<string> GetAllPredictions(string keywordStartsWith)
{
//TODO: implement real search here!
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["RaiseFantasyLeagueConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("[dbo].[findEnglishTeams]", conn);
cmd.CommandType = CommandType.StoredProcedure;
string searchTerm = keywordStartsWith;
SqlParameter searchTermParam = new SqlParameter("#searchterm", searchTerm);
cmd.Parameters.Add(searchTermParam);
IList<string> output = new List<string>();
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dReader.HasRows)
{
while (dReader.Read())
{
output.Add(dReader["englishTeamName"].ToString());
}
return output;
}
else
{
return output;
}
}
}
I need to get the ID of the values i am populating the drop down with, how is this possible?
Since you are populating this on the Client Side using an Ajax request, you are going to have to either:
Get the selected value by writing it to a html input type=hidden element and reading it on the server side when the form posts back. Just don't forget to make the input type=hidden element a server-side control by adding runat="server"
Submit the selected value via another Ajax request.
Read the selected values using the Request.Params collection, using the listbox's name as the Key. Something like:
var selectedValues = Request.Params["select_box_name"];
You won't be able to simply use ListBox.SelectedValue because the values won't be found in the ViewState since you are populating it via Ajax.
I'd go with option 3...
Hope the something like this serves your need better

Jquery Auto complete extender not working after postback

Im using jQuery Autocomplete using Web Service in ASP.Net.I've used the autocomplete to filter employeecode.When the page loads autocomplete works fine,but after when i click the search button autocomplete is not working properly.
I think the problem lies in document.ready function,so when the page loads it works fine,But i've to use autocomplete after the buttonclick event also.
How can i do this ???
Heres my jQuery Autocomplete
<link href="../AutoComplete/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../AutoComplete/jquery.min.js" type="text/javascript"></script>
<script src="../AutoComplete/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + 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('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
});
</script>
Markup
<td align="right">
<asp:Label ID="lblEmpCodeSrch" runat="server" Text="EmpCode" CssClass="label"> </asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmpCodeSrch" runat="server" Width="250px" ToolTip="Enter Employeecode"></asp:TextBox>
<asp:Button ID="bttnSearch" runat="server" CssClass="submit" Height="23px" Text="Search" onclick="bttnSearch_Click" />
</td>
ButtonSearch Codebehind
protected void bttnSearch_Click(object sender, EventArgs e)
{
clsEmp.EMPLOYEEID =txtEmpCodeSrch.Text.Trim()==""? 0:Convert.ToInt32(hFieldEmpId.Value);
DataTable dtEmp = clsEmp.GetDetails();
if (dtEmp.Rows.Count > 0)
{
hFieldEmpId.Value = "";
// txtEmpCodeSrch.Text = "";
if (ViewState["Sort"] != null)
{
DataView dView = new DataView(dtEmp);
dView.Sort = ViewState["Sort"].ToString();
gdView.DataSource = dView;
gdView.DataBind();
}
else
{
gdView.DataSource = dtEmp;
gdView.DataBind();
}
}
}
When you have an UpdatePanel, after the update of the data, you also need to re-initialize the javascript, because the old one is not longer working, because the struct of your html page have change, the dom have change.
The UpdatePanel is giving some function to do that on client side, and your code will be as:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Place here the first init of the autocomplete
InitAutoCompl();
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel re-init the Autocomplete
InitAutoCompl();
}
function InitAutoCompl() {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + 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('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
}
</script>
I tell you that I could solve the problem by adding a Triggers within the UpdatePanel tag, thus achieves the desired behavior in my case. I hope you can serve you as me helped me.
<ajax:UpdatePanel>
<ContentTemplate>
//My label fire autocomplete
<asp:TextBox id="MyLabelForAutoComplete" runat="server"/>
// Other Html Tags...
<Triggers>
<ajax:PostBackTrigger ControlID="MyLabelForAutoComplete">
</Triggers>
</ajax:UpdatePanel>

Categories

Resources