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!
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'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 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 created a jQuery modal password dialog box to redirect to a page for password validation.
The modal dialog appears alright, but instead of executing the method that handles the password validation it instead shows the error [object Object] on a the browsers alert dialog. I'm trying to figure out what I'm doing wrong here.
Below is my code:
JavaScript/jQuery
$(document).on("click", "[id*=lnkView1]", function() {
$("#dlgPassword").dialog({
title: "View Details",
buttons: {
Go: function() {
var valPassword = $("[id*=cpgnPassword]").val();
var hdfCamId = $('#<%=rptCampaigns.ClientID %>').find('input:hidden[id$="hdfCampaignID"]').val();
$("[id*=hdfCampaignID2]").val(hdfCamId);
//var jsonObj = '{password: "' + valPassword + '"}';
var res;
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{password: "' + valPassword + '"}',
dataType: 'json',
url: 'CampaignsList.aspx/ValidatePasswordWM',
success: function(data) {
alert('successful')
},
error: function(err) {
alert(err.toString());
}
});
$(this).dialog('close');
}
},
modal: true
});
return false;
});
Code-Behind
protected void ValidatePassword(object password)
{
var campaign = new CampaignsService().GetByCampaignId(hdfCampaignID2.Value);
if (campaign != null)
{
if (campaign.Password.Equals(password))
Response.Redirect("CampaignDetails.aspx?CampaignID=" + hdfCampaignID2.Value);
}
}
[WebMethod]
public static void ValidatePasswordWM(object password)
{
CampaignsList page = new CampaignsList();
page.ValidatePassword(password);
}
Can someone help me figure out what's wrong?
You need the appendTo property on your dialog so it gets added to the form properly.
$("#dlgPassword").dialog({
title: "View Details",
appendTo: "form",
buttons: {
...
Instead of err.toString(), try err.message
This code shows a products cadastre at jQuery UI. When OK button pressed, re-populate dropdownlist.
Javascript:
$dialog = $("#dlgCadastroProduto").dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
Ok: function () {
$(this).dialog("close");
$("#lstProducts").empty();
$("#lstSelectedProducts").empty();
$.ajax({
type: "GET",
url: '/Produto/jsonLoad',
async: true,
dataType: 'json',
success:
function (data) {
//alert('sucesso');
$.each(data, function (index, value) {
//insere elemento na droplist
$("#lstProducts").append('<option value='+value.ID+'>'+value.Descricao+'</option>')
});
},
error: function (data) {
//alert(data);
}
});
}
}
});
$("#btnCadastroProduto").button().on("click", function () {
$dialog.dialog("open");
});
Code-Behind at Controller:
public JsonResult jsonLoad()
{
var lista = _produtoBLL.FindAll();
var xpto = lista.Select(x => new { Id = x.ID, Descricao = x.Descricao });
return Json(xpto, JsonRequestBehavior.AllowGet);
}
I hope i have helped
This is just sample code you can you with yours
Client Side
var mparam = "{param1:'" + mvar1 + "',param_n:'" + mvar_n + "'}";
$.ajax({
type: "POST",
url: "file_name.aspx/web_method",
data: mparam,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
try {
var msdata = JSON.parse(Response.d);
if (msdata.err == "0") {
location.replace("newlocation");
}else{
alert("Error:" + msdata.msg);
}
} catch (e) {
alert("Error in JSON parser error:" + e.description);
}
},
error: function (medata) {
alert("Internal Server Error:" + medata);
}
});
Server Side
[System.Web.Services.WebMethod]
public static string web_method(string param1, string param_n)
{
string strerror = "0", strmessage = "";
try
{
strerror = "0";
}
catch (Exception ex)
{
strerror = "2";
strmessage = ex.Message;
}
return "{\"err\":\"" + strerror + "\",\"msg\":\"" + strmessage + "\"}";
}
I have some JavaScript that calls a function to repopulate a drop down list. There are 2 calls that populate 2 different drop down lists. The both work fine in local Dev. On the server only one works. The one Errors out. I remote debugged and the call reaches the function and the function returns the proper results. Its after it leaves the function that the error occurs. The application is asp.net mvc 3 the server is windows server 2008 iis7.
How can i narrow down what is causing the issue.
<script type="text/javascript">
function getSects(abbr) {
$.ajax({
url: "#Url.Action("SectionSwitch", "Assets")",
data: { abbreviation: abbr },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
// var test = JSON.parse(data);
//alert(test);
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.sectionNum + "\">" + item.sectionname + "</option>";
});
$("#Asset_Section_SectionKey").html(items);
}
});
}
function getDivs(abbr) {
$.ajax({
url: "#Url.Action("DivisionSwitch", "Assets")",
data: {abbreviation: abbr},
dataType: "json",
type: "POST",
error: function() {
alert("An error occurred.");
},
success: function (data2) {
// var test = JSON.parse(data);
//alert(test);
var items = "";
$.each(data2, function(i, item) {
items += "<option value=\"" + item.DivisionKey + "\">" + item.DivisionDescription + "</option>";
});
$("#Asset_Section_Division_DivisionKey").html(items);
}
});
}
$(document).ready(function(){
$("#Asset_Section_Division_Department_DepartmentKey").change(function () {
var abbr = $("#Asset_Section_Division_Department_DepartmentKey").val();
getDivs(abbr);
});
$("#Asset_Section_Division_DivisionKey").change(function () {
var abbr = $("#Asset_Section_Division_DivisionKey").val();
getSects(abbr);
});
});
</script>
Its the function getDivs that is throwing the error. Here are the functions:
public ActionResult DivisionSwitch(int abbreviation)
{
var newdivision = from f in db.Divisions
where f.DepartmentKey == abbreviation
select f;
return Json(newdivision);
}
public ActionResult SectionSwitch(int abbreviation)
{
var newsection = (from t in db.Sections
where t.DivisionKey == abbreviation
select new sectionInfo { sectionNum = t.SectionKey, sectionname = t.SectionDesciption });
return Json(newsection);
}
Change your error properties on your ajax methods to take 3 parameters (jqXHR, textStatus, errorThrown) and alert the errorThrown and textStatus:
error: function (jqXHR, textStatus, errorThrown) {
alert("Error, status: " + textStatus + " error: " + errorThrown);
},
Set up an error handler and see what it has to say
$( document ).ajaxError(function(event, jqxhr, settings, exception) {
console.log(jqxhr);
console.log(exception);
});
The error part of your $.ajax can accept three parameters of type jqXHR, textStatus, errorThrown.
The first parameter is an object of type jqXHR, the other two are strings. You could use jqXHR.responseText to see the error.
$.ajax({ // Some settings
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
// or
console.log(jqXHR);
}
According to jQuery web site, their example suggests following:
$.ajax({ // your settings
}).done(function(data, textStatus, jqXHR) {
// Handle success
}).fail(function(jqXHR, textStatus, errorThrown) {
// Handle error here
});
For more information have a look at jQuery.ajax() and read the Depreciation section.
I appreciate all the help but i decided to rewrite what was being returned similar to what the working call was returning. Apparently the server had a problem with what was being returned.
public ActionResult DivisionSwitch(int abbreviation)
{
var newdivision = from f in db.Divisions
where f.DepartmentKey == abbreviation
select f;
return Json(newdivision);
}
public ActionResult SectionSwitch(int abbreviation)
{
var newsection = (from t in db.Sections
where t.DivisionKey == abbreviation
select new sectionInfo { sectionNum = t.SectionKey, sectionname = t.SectionDesciption });
return Json(newsection);
}
I have now changed to code to this:
public ActionResult DivisionSwitch(int abbreviation)
{
var newdivision = (from f in db.Divisions
where f.DepartmentKey == abbreviation
select new DivisionInfo { DivisionNum = f.DivisionKey, Divisionname = f.DivisionDescription });
return Json(newdivision);
}
I just created a new class to store the result in and narrow it down to the two feilds required.
public class DivisionInfo
{
public int DivisionNum { get; set; }
public string Divisionname { get; set; }
}