Using jquery Autocomplete on textbox control in c# - c#

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.

Related

JQuery Ajax function not calling backend method in DNN

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.

Trying to pass data through jquery ajax facing issue

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}})

how to call jquery ajax to c# page

How to call jquery ajax to c# page there is no response from visual studio tried through break point
first tried with Big one no response from C# side(ProfitCentersNameInsert) function then tried another simple type (apply) function but no response from both methods
just commented the below lines on Ajax
// url: "ProfitCentersScreen.aspx/ProfitCentersNameInsert",
// data: "{'ProfitCenterName':'" + ProfitCenterName + "'}",
JS Code
$(function() {
profit.onRefresh()
$( "#btnAdd" ).click(profit.onClickSave);
});
var profit = {
onRefresh: function(){},
onClickSave: function(){
var ProfitCenterName =$('#txtProfitCenter').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
// url: "ProfitCentersScreen.aspx/ProfitCentersNameInsert",
url: "ProfitCentersScreen.aspx/apply",
// data: "{'ProfitCenterName':'" + ProfitCenterName + "'}",
data:'{}',
async: false,
success: function (response) {
alert( response );
alert(ProfitCenterName);
$('#txtProfitCenter').val('');
alert("Record saved successfully..!!");
},
error: function () {
alert("Error");
}
});
}
};
C# Code
[WebMethod]
public static string ProfitCentersNameInsert(string ProfitCenterName)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=192.168.0.133;User Id=hll; " + "Password=hll;Database=checking_DB;"); //+ "Pooling=true;MaxPoolSize=100;Timeout=20;"
try
{
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("Insert into tbl_Profit_Centers(Profit_Center_Id,Profit_center_Name) Values(default,#ProfitCenterName)", conn);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#ProfitCenterName", ProfitCenterName);
command.ExecuteNonQuery();
conn.Close();
return "Success";
}
catch (Exception ex)
{
return "failure";
}
}
[WebMethod]
public static string apply()//method must be "pulic static" if it is in aspx page
{
return "Hi";
}
try This
url: "ProfitCentersScreen.aspx",
data: {ProfitCenterName: ProfitCenterName}
Try below points, it should work :
1) if your page is at root level of project then the url should be like below :
url: "/ProfitCentersScreen.aspx/apply"
OR
url: "../ProfitCentersScreen.aspx/apply"
2) stringify your parameter
data: JSON.stringify({})
3) Finally add this parameter
dataType: "json",
Try using response.d in your success
success: function (response) {
alert(response.d);
alert("Record saved successfully..!!");
},
Here's pseudo code a simple jQuery Ajax call
jQuery:
$("#bntAJax").on('click', function (e) {
$.ajax({
type: "POST",
// your webmethod
url: "AjaxFunction/myFunction.asmx/apply",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall() {
}
e.preventDefault();
});
WebMethod :
[WebMethod]
public string apply()
{
return "Hello";
}

How to call webmethod in Asp.net C#

I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

auto complete on asp.net control

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..

Categories

Resources