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>
Related
NOTE: I did search the forums but didn't find anything that matched my issue or worked.
Hi all,
I'm trying to make a simple call from an asp.net web form using json & ajax to a method in the code-behind page but it's returning that page html instead of the value from the method.
Here is the method in the code-behind:
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 Tags
{
public partial class AJAX3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string CalculateSum(Int32 Num1, Int32 Num2)
{
Int32 Result = Num1 + Num2;
return Result.ToString();
}
}
}
Here is my web form:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AJAX3.aspx.cs" Inherits="Tags.AJAX3" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call asp.net server side page methods using jQuery AJAX & json</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCalculate").click(function () {
//Get values from textboxes that will be passed to function
var num1 = $('#txtFirstNumber').val();
var num2 = $('#txtSecondNumber').val();
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
//Url is the path of our web method (Page name/function name)
url: "AJAX3/CalculateSum",
//Pass values to parameters. If function have no parameters, then we need to use data: "{ }",
data: "{'Num1':'" + num1 + "', 'Num2':'" + num2 + "'}",
//called on ajax call success
success: function (result) {
$('#dvMsg').text("Sum of " + num1 + " and " + num2 + " = " + result);
},
//called on ajax call failure
error: function (xhr, textStatus, error) {
$('#dvMsg').text("Error:" + error + ", xhr: " + xhr + ", textStatus: " + textStatus);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Enter First Number:</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server" Text="22" /></td>
</tr>
<tr>
<td>Enter Second Number:</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server" Text="33" /></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnCalculate" Text="Calculate" runat="server" OnClientClick="return false;" />
<div id="dvMsg"></div>
</td>
</tr>
</table>
</div>
</form>
</body>
My goal is to return a string and not a JSON object.
What am I doing wrong?
Thanks!
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
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
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;
}
}
}
I have made my own little chat. It it basicly a jQuery that reloads a div by inserting another .aspx site into it.
This is my .aspx site:
<%# Page Title="" Language="C#" MasterPageFile="~/holdOversigt.Master" AutoEventWireup="true"
CodeBehind="chat.aspx.cs" Inherits="HB.chat1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var reloadtime = 3000;
function load() {
$.ajax({
url: "chat-Content.aspx",
context: document.body,
success: function (data) {
document.getElementById('chat').innerHTML = data;
setTimeout('load()', reloadtime);
}
});
}
window.onload = function () {
setTimeout('load()', reloadtime);
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h1 style="text-align: center; color: #005da3; font-weight: bold">
<strong>Chat rum</strong></h1>
<div id="chat" class="fisk" style="width: 500px; height: 500px">
</div>
<br />
<asp:TextBox ID="txbMessege" runat="server"></asp:TextBox>
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
</asp:Content>
THis is the site it inserts into the div:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="chat-Content.aspx.cs" Inherits="HB.chat_Content" %>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lbChat" runat="server" Rows="10" Width="400px"></asp:ListBox>
</div>
</form>
This is the sites codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HB
{
public partial class chat_Content : System.Web.UI.Page
{
grjenie31Entities gr;
protected void Page_Load(object sender, EventArgs e)
{
gr = new grjenie31Entities();
var query = from es in gr.chats
where es.id > ((from esh in gr.chats select esh.id).Max() - 15)
orderby es.timestamps descending
select es;
List<chat> list = new List<chat>();
foreach (chat chat in query)
{
list.Add(chat);
}
for (int i = 0; i < list.Count; i++)
{
lbChat.Items.Add("[" + list[i].timestamps + "] " + list[i].personID.ToString() + ": " + list[i].besked);
}
this.lbChat.SelectedIndex = this.lbChat.Items.Count - 1;
}
}
}
I can add new lines until it loads... but when the listbox is showed on the site it give me the follow error:
The state information is invalid for this page and might be corrupted.
Anybody got any idea what i can do about it??
It seems you inserted all page content even ViewState hidden tags.
I think it's better to clear your response and write your html tags which you needed in chat.
Response.Clear();
Response.ContentType = "text/plain";
Response.Write(GetChatResult());
Response.End();