Implementing Autocomplete textbox in ASP.NET - c#

I am trying to get an autocomplete textbox working for my website on a web form. This is to autocomplete the textbox with house names once the user has started typing. The sql database is connected and the ado.net model is all set up. I just can't seem to figure out why it is not working.
The aspx page is below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#<%=txtHouseName%>").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebForm1.aspx/GetHouseName",
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item }
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Auto Complete Textbox without using Web Service</h3>
<table>
<tr>
<td>House Name: </td>
<td>
<div class="ui-widget" style="text-align:left">
<asp:TextBox ID="txtHouseName" runat="server" Width="350px" CssClass="textboxAuto" Font-Size="12px" />
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
and this is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Houses_of_Mayo
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetHouseName(string pre)
{
List<string> allHouseName = new List<string>();
using (HOMEntities h = new HOMEntities())
{
allHouseName = (from a in h.Houses
where a.Name.StartsWith(pre)
select a.Name).ToList();
}
return allHouseName;
}
}
}

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

passing bulk array values to codebehind(cs) using ajax

I have to pass bulk array values to code behind (cs) using ajax i had researched a lot and used this code but it didnot worked for me below is the code that i used what i need is i need to pass bulk array values in code behind(cs) using ajax
JS
<head runat="server">
<title></title>
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
C#
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;
namespace PassingValueFromJavascriptToCs
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
// Do whatever processing you want
// However, you cannot access server controls
// in a static web method.
}
}
}
First of all the button for aspx is sending your aspx form to a postback so that you would need to change the aspx like this
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
The reason the foo method returns false that you dont want to make your button start a postback. I also added another property UseSubmitBehavior="false" to guarantee it.
The scripts section i changed the values object to a real array and then when sending data , i converted it to json with values object inside. This code will work in your example just fine
Edit : For the working version on my tests
The aspx page (trimmed details to the master page)
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
function test() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/test", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
debugger;
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
<asp:Button ID="Button3" UseSubmitBehavior="false" OnClientClick="return test();" runat="server" Text="Deneme" />
</asp:Content>
The RouteConfig and original method
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}
Well at least one issue is your url is "Default.aspx/Done" but the method appears to be on WebForm3.aspx/Done.
What actually happens with your code? Does it error?

Autocomplete TextBox Not working with Database values in asp.net

I have a textbox and a database.Every time the user types something in the textbox it can not work with database.
here is my default.aspx.cs code file i want your kind help thanks in advance :)
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.Web.Script.Services;
namespace dotnetawsome
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScripMethod(ResponseFormat = ResponseFormat.Json)]
public static List<TopCompany> GetCompanyName(String pre)
{
List<TopCompany> allCompany = new List<TopCompany>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
allCompany = (from a in dc.TopCompanies
where a.CompanyName.StartWith(pre)
select a).ToList();
}
return allCompany;
}
}
}
here is my default.aspx file
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="dotnettest._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" src="script.js"></script>
<script src="jquery\jquery.js"></script>
<link rel="stylesheet" href="css/jquery-ui.css" />
<script src="js/jquery-1.8.3.js" type="text/javascript" language="javascript"></script>
<script src="js/jquery-ui.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript" language="javascript">
<style>
.ui-autocomplete
{
font-size: 11px;
}
</style>
<script language="javascript" type="text/javascript">
$(function (){
$('#<%=textCompanyName.ClientID %>').autocomplete({
source: function(request,response){
$.ajax ({
url: "default/GetCompanyName",
data: "{'pre' :'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data){
response($.map(data.d,function(item){
return{
CompanyName: item.CompanyName,
Industry: item.Industry,
json: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert(textStatus);
}
});
},
focus: function (event, ui){
$('#<%=textCompanyName.ClientID %>').val(ui.item.CompanyName);
return false;
},
select: function(event ui){
$('#<%=textCompanyName.ClientID %>').val(ul.item.CompanyName);
return false;
},
}).data("ui-autocomplete")._renderItem= function(ul, item){
return $("<li>")
.append("<a>Company:" +item.CompanyName +"<br> Industry: " + item.Industry + "</a>")
.appendTo(ul)
};
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<table>
<tr>
<td> Card Name </td>
<td>
<div class="ui-widget" style="text-align:left">
<asp:TextBox ID="textCompanyName" runat="server" CssClass="textboxAuto" Width="350px" Font-Size="12px"></asp:TextBox>
</div>
</td>
</tr>
</table>
</asp:Content>

C# Webmethod unable to be called with JQuery AJAX

I am trying to call a webmethod I created. The problem I'm having is that the ajax call never calls my webmethod; this is strange to me because I have another webmethod located in the same file with the same return type and parameters that is able to be referenced fine in the "url" definition of the ajax call.
My aspx document consists of the following:
File name CS.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="_Default" %>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script>
function ShowCurrentTime() {
if(document.getElementById("txtUserName").value == "" && document.getElementById("app_name").value == ""){
alert("One of the fields must be filled out");
return 0;
}
$.ajax({
type: "POST",
url: "CS.aspx/getAppId",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
var y = document.getElementById("test");
y.innerHTML = response.d;
}
</script>
<body>
<form id="form1" runat="server">
<div>
<table style="background-color:#fcfcfc; width:30%;">
<tr>
<td><b>Application ID:</b> </td>
<td><asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br /></td>
</tr>
<tr>
<td><b>Application Name:</b></td>
<td><asp:TextBox ID="app_name" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><input id="btnGetTime" type="button" value="Search"
onclick = "ShowCurrentTime()" /></td>
</tr>
</table>
<p id="test"></p>
</body>
</html>
My web method looks like the following with the filename CS.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.Script.Serialization;
public partial class _Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string getAppId(string appName) {
return "this is a string";
}
}
I've put a breakpoint at the return statement, just to make sure that the method is even called, while in debug mode, and have had no luck.
Make sure you have a reference to jQuery if you want to make a jQuery ajax call.
Also, the parameters of your WebMethod need to match the parameter name you are passing in. The parameter is appName:
$.ajax({
type: "POST",
url: "CS.aspx/getAppId",
data: '{appName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (response) {
alert(response.d);
}
});
And in the WebMethod it is appName as well:
[System.Web.Services.WebMethod]
public static string getAppId(string appName)
{
return "this is a string";
}
In your code, there is a mismatch.
I would also make a habit of closing your div and form tags.
You need to place this service in a WCF or ASMX service and create a JavaScript proxy for it. See http://msdn.microsoft.com/en-us/library/bb532367(v=vs.90).aspx

Internal Error on jQuery Autocomplete ajax call to ASP.NET

For some reason I am getting an Internal Error (500) when I am attempting to get a List of strings from an ASP.NET method. I have tried many different ways of writing it and an entire page of google is all purple but to no avail. Perhaps maybe you guys can spot something I am completely missing.
Here is the HTML/Javascript
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="messaging.aspx.cs" Inherits="xxx.messaging" %>
<asp:Content ID="Content1" ContentPlaceHolderID="content" runat="server">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function () {
//$(".selectable").selectable();
$('[id$="username_textbox"]').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Services.asmx/getFollowingUsernames",
dataFilter: function (data) { return data; },
data: "{'prefixText': '" + request.term + "' }",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (xhr, textStatus, errorThrown) {
var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + xhr.statusText + " : " + xhr.status;
if (xhr.status != "0" || errorThrown != "abort") {
alert(errorMessage);
}
}
});
},
search: function (event, ui) {
$('.spinner').show();
},
response: function (event, ui) {
$('.spinner').hide();
},
minLength: 1
});
});
</script>
<div class="messaging_wrapper">
<div class="conversations_list" runat="server">
<asp:Button ID="new_message" runat="server" Text="New Message" />
<ol id="conversation_ol" class="selectable" runat="server">
</ol>
</div>
<div id="conversation_wrapper" class="converation_div" runat="server">
<div id="conversation_head">
<asp:TextBox ID="username_textbox" runat="server"></asp:TextBox>
<img src="images/ajax-loader.gif" style="display:none" class="spinner" />
</div>
</div>
</div>
</asp:Content>
Here is the WebService code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace xx.App_Code
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 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 Services : System.Web.Services.WebService
{
[WebMethod]
public List<string> getFollowingUsernames(string prefixText)
{
SessionAdapter sa = new SessionAdapter();
int id = sa.getUserID();
MembershipAdapter ma = new MembershipAdapter();
List<int> ids = new List<int>();
ids = ma.getUserFollowingList(id);
List<string> usernames = new List<string>();
foreach (int userID in ids)
{
usernames.Add(ma.getUserName(userID.ToString()));
}
return usernames;
}
}
}
Here is what the internal error is:
Seems kind of obvious now, but the line
// [System.Web.Script.Services.ScriptService]
should be un-commented
[System.Web.Script.Services.ScriptService]

Categories

Resources