I'm trying to pass some data (parameter) from client side (html) to the server side (C# code-behind) to a method, this is done using AJAX in JSON format, but I'm getting the following error:
Unknown Web Method
my AJAX code is:
var jsonObj = { "sCriterion": sCriterion };
$.ajax({
type: "POST",
url: "NewToken.aspx/GetSelection",
data: jsonObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert(data);
alert("We returned: " + result);
}
});
and this is my code-behind method:
[WebMethod]
private static string GetSelection(string selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
var jsonObj = json.Serialize("proceeded");
return jsonObj;
}
The method should be public static to work. Not private !
[WebMethod]
public static string GetSelection(string selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
var jsonObj = json.Serialize("proceeded");
return jsonObj;
}
Your GetSelection method must be public, but you set it private.
Related
I have some trouble to send an array of string using ajax to a C# controller.
I tried many things but i can't make it works.
Here is my C# controller :
[HttpPost]
[Route("getavailabilities")]
[Authorize]
public IActionResult GetAvailabilities(string[] data)
{
return StatusCode((int)HttpStatusCode.OK, new
{
data = ""
});
}
Then my ajax call :
function apiExecuteRequest(callback, uri, type, data) {
$.ajax({
url: uri,
type: type,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: (apiReply) => {
callback(apiReply);
},
failure: (xmlHttpRequest, textStatus, errorThrown) => {
callback({ isSuccess: false, error: textStatus + " " + errorThrown, message: xmlHttpRequest.responseJSON });
},
error: (xmlHttpRequest, textStatus, errorThrown) => {
callback({ isSuccess: false, error: textStatus + " " + errorThrown, message: xmlHttpRequest.responseJSON });
}
});
}
function apiExecuteAuthenticatedRequestAsync(callback, uri, type, data) {
apiGetTokenAsync((token) => {
$.ajaxSetup({
beforeSend: (xhr) => {
xhr.setRequestHeader("Authorization", "bearer " + token);
}
});
apiExecuteRequest(callback, uri, type, data);
});
To get my array i use :
var data = this.values2.map(function (item) {return item.ItemId;})
apiExecuteAuthenticatedRequestAsync((response) => {
...
}, apiUrl + 'dashboard/getavailabilities', "POST", data);
What i get is everytime Null.
When i set the parameter to object or dynamic i get : {object}.
I really need your help, and thank you for any advice and help you would provide me.
As you know that the dataType of the request is application/json. So you need to convert the data to Json String using JSON.stringify like so:
var data = this.values2.map(function (item) {return item.ItemId;})
apiExecuteAuthenticatedRequestAsync((response) => {
...
}, apiUrl + 'dashboard/getavailabilities', "POST", JSON.stringify(data));
I met the big one problem with jQuery autocomplete with source .asmx file
here's my code:
$("#enterprise_search").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Services/EnterprisePortal/wsGetFAQQuestions.asmx/GetQuestionsByWord",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "Word="+$('#enterprise_search').val(),
dataType: "json",
success: function (data) {
console.log('Data recieved');
response($.map(data.d, function () {
return {
label: item.Name + '(' + item.Value + ')',
value: item.Name
}
}))
},
error: function (xhr, msg) {
console.log('Database connect error: ' + msg);
}
});
},
minLength: 1,
select: function (e, ui) {
var result = item.Name;
var answer = item.Value;
$('#search-results').append('<p>' + result + ' : ' + answer + '</p>');
},
close: function () {
$("#enterprise_search").val('');
}
});
there is a method of c# or whatever it is (that code is not mine, just for you to take a look)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] //Specify return format.
public string GetQuestionsByWord(string Word)
{
//JavaScriptSerializer YourSerializer = new JavaScriptSerializer();
//return YourSerializer.Serialize(FAQsCOL);
Dictionary<string, string> FAQsCOL = clsFAQBLL.GetFAQCOLByWordInQuestionAnswer(Word);
//Dictionary<string, string> ReturnLinks = FAQsCOL.ToDictionary(m => string.Format("{0}?{1}={2}", clsParameters.clsPages.ENTERPRISE_PORTAL_FAQs, clsParameters.clsQueryString.FAQ_ID, m.Key), m => m.Value);
return JsonConvert.SerializeObject(FAQsCOL);
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] //Specify return format.
public string GetQuestionByQuestionId(int FAQId)
{
Linq.General.FAQ CurrentFAQ = clsFAQBLL.GetFAQByFAQId(FAQId);
FAQ FAQ = new FAQ();
if (CurrentFAQ != null)
{
FAQ = new FAQ(CurrentFAQ.Question, CurrentFAQ.Answer);
}
return JsonConvert.SerializeObject(FAQ);
}
after all of these I get in console (search for '2'):
jquery-2.1.4.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in {"5":"שאלה - 17","11":"מהו הנוהל לגבי מתמחה אשר מנהלו מסרב לחתום על טופס ההרשמה לבחינה?","20":"מהו נוהל הזכאות לגשת לבחינות התמחות?"}
i tried to push data into array (search for '1'), that's the look: d
:
"{"2":"שאלה 2","3":"שאלה 2","4":"שאלה 2","11":"מהו הנוהל לגבי מתמחה אשר מנהלו מסרב לחתום על טופס ההרשמה לבחינה?","20":"מהו נוהל הזכאות לגשת לבחינות התמחות?"}"
can anyone help me with this? I've lost a lot of time for this sick thing
can't understand is it a mistake or something in webservice or in my jquery function
Replace
data: "Word="+$('#enterprise_search').val(),
with
data: {"Word": $('#enterprise_search').val() },
And again after couple of hours mind**ng gives me an answer by myself:
var searchValue = JSON.stringify($('#enterprise_search').val());
data: {Word:searchValue},
success: function (datas) {
console.log('Data recieved: ' + datas.d);
var data = JSON.parse(datas.d);
$.each(data, function (index, value) {
$('#search-results').append('p' + index + ': ' + value + '</p>');
});
}
hope helps someone, cause I'm not the best on this thing, but shall be ;)
I'm trying to send a json list populated with the id's from the 'data-seq' attribute only when the 'value' == true.
I have tried out a lot solution but it keeps getting me error messages, the most common are "there is no parameterless constructor for the type string" when using string[] or "string is not supported for deserialization of an array" when using string as code-behind parameter in the WebMethod.
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var obj = {
id: $(this).attr("data-seq")
};
json.push(obj);
});
json = JSON.stringify({ jsonList: json });
console.log(json); // {"jsonList":[{"id":"38468"},{"id":"42443"},{"id":"42444"}]} (the right id's are getting stored)
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: json,
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
// Code-Behind
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
// string: string is not supported for deserialization of an array
// string[]: there is no parameterless constructor for the type string
}
You are just sending IDs so send them as comma-separated string like this:
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var id = $(this).attr("data-seq")
json.push(id);
});
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: '{jsonList: "' + json + '" }',
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
And Code-Behind:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
List<string> ListOfIDs = jsonList.Split(',').ToList();
}
I have the following ajax call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/LoadCount.aspx/GetCounts",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
alert(myObj.length);
for (var i = 0; i < myObj.length; i++) {
alert(myObj[0]);
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I am getting undefined when I alert the length
Here's my Method in my LoadCount.aspx
[WebMethod]
public static string ObtenerContador()
{
List<MenuItem> menu =(List<MenuItem>)HttpContext.Current.Session["MenuItems"];
Dictionary<string, int> dic = new Dictionary<string, int>();
foreach (MenuItemAMostrar item in menu)
{
dic.Add(item.ControlID,1);
};
return new JavaScriptSerializer().Serialize(dic); //or any other suggested serialization method
}
this is what I am getting in the success function:
{"MenuCLESAAsignar":1,"MenuOCGestores":1,"MenuOcAAutorizar":1,"MenuOcAAutorizarBanco":1,"MenuOCGestoresObservadas":1,"MenuCLESActivos":1,"MenuParametros":1,"MenuCLESConAddendaAAprobarSup":1,"MenuPendienteAprobacion":1,"MenuConsultaCLES":1}
The question is, how do I deserialize that dictionary in my ajax success function?
Once deserialized, how do I populate it, obtaining the data?
thanks!
As somebody else mentioned, you just use JSON.parse() to parse the data.
From there it just creates an object, and you can access the data with ..
Like so:
http://jsfiddle.net/SJGLF/1/
var myData = JSON.parse(jsonData);
for(var i in myData)
{
console.log(i + " = " + myData[i]);
}
Are you looking for this?
success: function (data)
{
var myObj = JSON.parse(data.d);
},
$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "MyService.asmx/GetCompletionList",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
This is my jQuery code and WebService method. Can any one help me?. GetCompletionList WebService method returns list of string but autocomplete on TextBox shows undefined for all values
public List<string> GetCompletionList(string prefixText)
{
RegistrationBAL _rbal = new RegistrationBAL(SessionContext.SystemUser);
DataSet ds = new DataSet();
_rbal.LoadByContextSearch(ds, prefixText);
List<string> myList = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
myList.Add((string)row[0]);
}
return myList.ToList();
}
Try to change the data in the ajax call as follows
if the auto complete is done for an asp control
data: "{'prefixText':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
or else give as follows
data: "{'prefixText':'" + document.getElementById("requiredID").value + "'}",
edited answer where the auto complete works
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
}
});
}
});
}
which resembles your ajax function but in server side I used the web service as below which the get values from the database
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetAutoCompleteData(string PhoneContactName)
{
List<string> result = new List<string>();
string QueryString;
QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("select DISTINCT PhoneContactName from PhoneContacts where PhoneContactName LIKE +#SearchText+'%'", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", PhoneContactName);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
result.Add(obj_result["PhoneContactName"].ToString().TrimEnd());
}
return result;
}
}
}
}
.. Hope this helps :D