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));
Related
In my view file, I'm making an ajax call as follows:
$.ajax(
{
url: '#Url.Action("LMTDetailDashboardList", "DetailUsage")',
dataType: "json",
data:
{
ServerID: ServerID,
LicenseId: LicenseId,
company: company,
fromDate: fromDate,
toDate: toDate,
fromhour: fromHour,
toHour: toHour
},
type: "GET",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
beforeSend: function () {
$("#divLoading").show();
},
success: function (data) {
LMTDetailDashboardChart(data, Zaxis);
return false;
},
#*error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},*#
//error: function (jqxhr, status, exception) {
// alert('Exception:', exception);
//},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
console.log('Could not get posts, server response: ' + textStatus + ': ' + errorThrown);
},
complete: function () {
$("#divLoading").hide();
$("#exportuserlist").show();
}
});
return false;
The controller code is as follows:
public JsonResult LMTDetailDashboardList(String ServerID, String LicenseId, String Company, String FromDate, String ToDate, String FromHour, String ToHour)
{
int nameLength = Company.Length;
int nameLength2 = ServerID.Length;
int nameLength3 = LicenseId.Length;
System.Text.ASCIIEncoding.ASCII.GetByteCount(Company);
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
TempData["Company"] = Company;
TempData["ServerID"] = ServerID;
TempData["LicenseId"] = LicenseId;
TempData["FromDate"] = FromDate;
TempData["ToDate"] = ToDate;
TempData["FromHour"] = FromHour;
TempData["ToHour"] = ToHour;
if (object.Equals(ServerID, null))
{
ServerID = "All";
}
try
{
var response = objLMTDAL.GetLMTDetailUsage(ServerID, LicenseId, Company, FromDate, ToDate, FromHour, ToHour);
if (!object.Equals(response, null))
{
objLMT.LMTDetailUsageList = response.ToList();
}
}
catch (Exception ex)
{
throw;
}
return Json(objLMT.LMTDetailUsageList, JsonRequestBehavior.AllowGet);
}
When the "company" value is smaller in length/size ajax call hits the controller action but when it is larger, it throws an error and it doesn't hit the controller method.
I have tried to rectify errors in many ways but not able to get it. With browser debugger, I am now getting following error. Error Screen
Note: "company" variable contains the comma separated values from the multi-select drop-down.
Kindly put some light on it.
The problem is because of the data length. The GET requests have length restrictions. That's why the ajax call not hitting the controller. You can use a POST instead of GET method. The POST requests have no restrictions on data length.
Change the 'type' using the following way:
type: "POST",
Your final script will be:
$.ajax(
{
url: '#Url.Action("LMTDetailDashboardList", "DetailUsage")',
dataType: "json",
data:
{
ServerID: ServerID,
LicenseId: LicenseId,
company: company,
fromDate: fromDate,
toDate: toDate,
fromhour: fromHour,
toHour: toHour
},
type: "POST",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
beforeSend: function () {
$("#divLoading").show();
},
success: function (data) {
LMTDetailDashboardChart(data, Zaxis);
return false;
},
#*error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},*#
//error: function (jqxhr, status, exception) {
// alert('Exception:', exception);
//},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
console.log('Could not get posts, server response: ' + textStatus + ': ' + errorThrown);
},
complete: function () {
$("#divLoading").hide();
$("#exportuserlist").show();
}
});
return false;
Good Luck!
I am trying to set the date in a Bootstrap datetime picker based on drop down list selection change. I am using a web method (C#) to return "start date" given a "certificate ID".
I tried using "text" data type instead of "json" but keep getting "Cannot convert object of type System.String to type System.Collections.Generic.IDictionary"
I searched for this error type and could not find something that would resolve this issue.
$("#ddlCertificate").change(function () {
....
debugger
setStartDate($("#ddlCertificate").val());
});
function setStartDate(certItemID) {
var param = JSON.stringify(certItemID, null, 2);
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: param,
}).done(function (result) {debugger
$("#tbStartDate").val(result.d);
}).fail(function (jqXHR, textStatus, errorThrown) {debugger
alert(textStatus + ' - ' + errorThrown);
});
}
Web Method:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string GetCertItemStartDate(string certID)
{
int iCertItemID = int.Parse(certID);
DateTime dtStartDate = CertItem.GetCertItemStartDate(iCertItemID);
string JSONresult;
JSONresult = JsonConvert.SerializeObject(dtStartDate);
return JSONresult;
}
The problem was the way the parameter was being passed. In ajax call, I had:
data: param,
and had to change it to:
$("#ddlCertificate").change(function () {
....
var certID = "{ 'certID': '" + $('#ddlCertificate').val() + "'}";
setStartDate(certID);
});
function setStartDate(certItemID) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: certItemID,
}).done(function (result) {
var startDate = JSON.parse(result.d);
setStartDate(new Date(startDate));
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown);
});
}
I'm trying to do a ajax request to my controller in C#, but it never reaches the controller - I get a type Error saying "query is undefined".
Here is my ajax script:
$(document).ready(function () {
$.ajax({
url: '/Account/GetAllGamesWithRoles',
type: 'POST',
data: {},
success: function (games) {
debugger;
Games = games;
BuildGames(games);
},
error: function() {
}
});
});
Here is my controller action:
[HttpPost]
public ActionResult GetAllGamesWithRoles()
{
var result = MockGames();
return new JsonResult{ Data = result, MaxJsonLength = Int32.MaxValue};
}
try this
$(document).ready(function () {
alert('called before ajax');
$.ajax({
url: "/Account/GetAllGamesWithRoles",
type: "POST",
data: {'test':'testcall'},
success: function (data) {
Games = data.Data;
BuildGames(Games);
},
error: function (request, textStatus, errorThrown) {
alert("Status: " + textStatus + "Error: " + errorThrown);
}
});
});
[HttpPost]
public JsonResult GetAllGamesWithRoles(string test)
{
var result = MockGames();
return Json{ Data = result, JsonRequestBehavior.AllowGet};
}
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.
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();
}