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..
Related
I am a beginner in programming, I have researched a few places to implement the jquery autocomplete. I managed to call postback to JSON GROUP method. But after success, I can't manage to get the JSON results or if I code it wrongly. Please help
Code
$(function () {
$("#txtGRP_CODE").autocomplete({
source: function (request, response) {
$.ajax({
url: '/AutoComplete/GRP_CODE',
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ 'prefix': '" + request.term + "'}",
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#txtGRP_CODE").val(i.item.value);
},
minLength: 1
});
});
Server Side
[HttpPost]
public JsonResult GRP_CODE(string prefix)
{
List<AutoCompleteController> listGroup = new List<AutoCompleteController>();
string sSQL = " SELECT * FROM icgrp WHERE GRP_CODE like '" + prefix + "%'";
DataTable dt = conn2.GetData(sSQL);
using (MySqlDataReader dr = conn2.ExecuteReader(sSQL))
{
//foreach (DataRow dr in ds.Tables[0].Rows)
while (dr.Read())
{
listGroup.Add
(new search
{
Name = dr["GRP_CODE"].ToString(),
Sr_no = dr["GRP_PART"].ToString()
}
);
}
}
//**I manage to populate listGroup but when passing it to the client side I can't get the Json data.
return Json(listGroup, JsonRequestBehavior.AllowGet);
}
Server Side
https://ibb.co/sVbKSYG
Client side
https://ibb.co/09CFXdW
Network Client Response
https://ibb.co/BB61dRd
Response
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /AutoComplete/GRP_CODE
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3282.0
I cannot get DotNetNuke to execute the backend code from my JQuery Ajax function.
I have the following JQuery code on my View.ascx file
I did try to change the URL to View.ascx/DeleteReviewData but no luck.
function deleteReview(ReviewID){
var ReviewIDToDelete = ReviewID;
$.ajax({
type: "POST",
contentType: "application/json",
url: "https://dnndev.me/Product-View/DeleteReviewData",
data: "{'deleteReviewID': '"+ ReviewIDToDelete +"'}",
datatype: "json",
success: function (data) {
alert("Delete successfull");
},
error: function (error) {
alert(error);
}
});
}
This is my back-end code which doesn't get executed on the View.ascx.cs file:
[System.Web.Services.WebMethod]
public static void DeleteReviewData(int deleteReviewID)
{
try
{
//Deletes a review from the database
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString()))
{
connection.Open();
using (SqlCommand command = new SqlCommand($"delete from ProductReviews where ReviewID = {deleteReviewID}"))
{
command.Connection = connection;
command.ExecuteNonQuery();
}
connection.Close();
}
}
catch(Exception ex)
{
throw;
}
}
If I should use MapHttpRoute. Does someone have an example, please?
I looked at the following post, but I am not sure about using RouteConfig.cs and extra headers and etc: https://www.dnnsoftware.com/answers/execute-an-action-by-calling-an-ajax-post
I currently get no Console errors. It goes to the success section.
When I hover over Type, ContentType or any one of those while debugging it says not defined. See example below. The site is using JQuery 01.09.01
2nd image
UPDATE
I have changed the URL which now gives me a 404 error: url: $.fn.GetBaseURL() + 'DesktopModules/ProductDetailedView/DeleteReviewData'
I also tried this URL path with adding API API/DeleteReviewData , but I get a [object Object] error as it shows a 404 error in the console.
This is an example:
$.ajax({
data: { "Id": IdToDelete },
type: "POST",
dataType: "json",
url: "/DesktopModules/{API-ProjectName}/API/Main/DeleteExpenseByID"
}).complete(function () {
//...
});
Api method:
[HttpPost]
[DnnAuthorize]
public void DeleteExpenseByID(int Id)
{
//...
}
You need to send a number so you dont need the "'" surrounding ReviewIDToDelete var.
Also check DeleteReviewData for a [POST] attribute, it seems to be a [GET] call.
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 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
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.