ASPNET. - Reponse code 500 when doing Ajax call produces - c#

i have write small application base aspnet with ajax
and i have function ajax look like that
//ajax code
function currentAccountApiToken(userId){
data = JSON.stringify({
"accountID": userId
})
$.ajax({
type: 'POST',
async: false,
url: '/Configurate/controller.aspx/getListApiKey',
data:data,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (result){
var data = JSON.parse(result.d);
console.log(data.result);
var isExec1 = (data.result[0].isExecute) == 1 ? true : false;
console.log(isExec1);
$('label#apiTokenOne').empty().append(data.result[0].apiToken)
toggleswitch(isExec1,'');
//parse data to element
$('label#apiTokenTwo').empty().append(data.result[1].apiToken)
var isExec2 = (data.result[1].isExecute) == 1 ? true : false;
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
// c# code
//get list profile
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string get_list_profiles_user(string _account_id)
{
var temp = new Entity.DBEntity.tblProfileUser();
temp._account_id = _account_id;
string _query_string = temp.get_profile_name();
List<Entity.DBEntity.tblProfileUser> _list_profiles = Configurate.sqlBuilder.get_list_profiles(_query_string, Configurate.DBConnection._mysqlcon);
return new JavaScriptSerializer().Serialize(new
{
_list_profiles
});
}
however, when i running code, the return http code 500 with error
jquery-3.3.1.js:9600 POST
http://xxx.xxx.xxx.xxx:88/Configurate/controller.aspx/get_list_profiles_user
profile.js:290 {"readyState":4,"responseText":"{\"Message\":\"There
was an error processing the
request.\",\"StackTrace\":\"\",\"ExceptionType\":\"\"}","responseJSON":{"Message":"There
was an error processing the
request.","StackTrace":"","ExceptionType":""},"status":500,"statusText":"Internal
Server Error"}
so please help me,
thanks !

Related

Why does my ajax call not returning my data from controller?

I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.

Chaining Controller Actions and/or promises in 1 button click

I currently have my project working about 75% of the time, I create report/reports add them to a zip, unzip them to a certain location. When I run this in debug mode it works correctly. When i run it normally sometimes the ajax will run out of order and it will try to unzip the file before its zipped (nothing is there). I have been doing trial and error with this trying many different methods to get this to work.
I tried multiple ways to do this: with the success: of ajax. I tried a .done promise after ajax. I tried a bool : if statement I tried many different conditions. It seems to finally be working in the correct order when i first open the project and select the records and the button click. Only 1 time it will do it successful.
When I try to select new records and run it a 2nd time the unzip folder isnt always created Or if it'll be created but will be empty (No reports unzipped to it).
Here is what I currently have which sometime works. Once I have this going good then I have to create the last step which will be to create an email and attach the document.
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs" : arrSelectedChks },
success: function () {
window.location = '/Service/DownloadAsZip/';
// DownloadAsZip?mimeType=' + data;
},
error: function (request, status, error) {
alert("Error Generating Files");
//+ request.responseText);
}
}).done(function () {
$.ajax({
type: "POST",
url: "/Service/UnZipDownload",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
//alert("success in unzip");
CallEmail();
}
})
});
Here is another way i been doing this.
if (isValid) { /* At least 1 record is selected */
var phaseOne = $.ajax({
type: "GET",
async: false,
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs": arrSelectedChks },
success: function (response) {
window.location = '/Service/DownloadAsZip';
successful = true
},
complete: function () {
if (successful)
isZipped = true;
}
});
}
$.when(phaseOne).always(function () {
if (isZipped) { /* Files are Zipped to start this phase */
$.ajax({
type: "POST",
async: false,
url: "/Service/UnZipDocument",
data: {},
contentType: "application/json; charset=utf-8",
traditional: true,
});
}
})
P.S. I have both Controller Actions UnZipDownload and UnZipDocument (both similar) if needing to see the action i will post.
You have to call your the second function only if the first is successful
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs" : arrSelectedChks }
}).done(function(){
window.location = '/Service/DownloadAsZip/';
// DownloadAsZip?mimeType=' + data;
$.ajax({
type: "POST",
url: "/Service/UnZipDownload",
data: {},
contentType: "application/json; charset=utf-8"
}).done(function(){
//alert("success in unzip");
CallEmail();
});
}).fail(function(){
alert("Error Generating Files");
//+ request.responseText);
});
So I have tried SO MANY DIFFERENT results to try to get this to work with the click of 1 button. BUT the only way I have found out a way to get this to work is to have 1 button to do the report creating and zipping of the files. Then to have a second button (mines currently in a modal) and on this button click I am unzipping the file and creating the email. I have not been able to do everything all in 1 call. When I try my unzip functions is being called before my zip function I have tried many different ways to try to not have this happen [success, .done(), deferred objects, javascript promises]
$('#btnGetChkEmail').on('click', function() {
var arrChkBoxes = [];
var arrSelectedChks = [];
var myJSON = {};
var phaseOne, phaseTwo;
var isValid = false;
var bool = false;
var isZipped = false;
//var unZipped = false;
var successful = false;
// Turn all selected checkbox T/F values into QuoteIDs
$("input:checked").each(function (index, value) {
arrChkBoxes.push($(value).val());
});
// Push all Selected QIDs on NEW ARRAY
$.each(arrChkBoxes, function (key, value) {
if (IsPositiveInteger(value)) {
arrSelectedChks.push(value);
}
});
if (arrSelectedChks.length === 0) { // Create Modal (Error ~ None ~ Selected)
isValid = false;
alert("No Records Selected");
} else {
isValid = true;
}
/* EDITION LIKE GETCHKS */
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs": arrSelectedChks },
success: function (response) {
window.location = '/Service/DownloadAsZip';
},
error: function (request, status, error) {
alert("Error Generating Reports");
}
}).done(function (data) {
/* Only way to do this 100% at the moment is to bring up a Button in a Modal */
var zipModal = $("#zipModEmail");
var modalHead = "<h3 class='modal-title'>Generate Email Messages</h3>";
var modalBody = "<span class='glyphicon glyphicon-ok-sign' style='font-size:5em; color:green;'></span>" +
"<p><b>Attach PDF's to email Confirmation</b></p>" +
"<p>Click 'OK' to Confirm</p>";
//var modalFoot = "";
zipModal.find(".modal-header").html(modalHead);
zipModal.find(".modal-header").addClass("alert-success");
zipModal.find(".modal-body").html(modalBody);
zipModal.modal("show");
});
}
$("#btnUnNemail").click(function (e) {
var myJSON = {};
var bool = false;
var ajaxCall = $.ajax({
type: "POST",
url: "/Service/UnZipDocument",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response.Status == "Unzipped") {
myJSON = { "Status": "Unzipped", "FilePath": response.FilePath, "FileName": response.FileName, "FileNames": response.FileNames };
bool = true;
}
$("#zipModEmail").modal("hide");
}
});
// Try switching to 'POST'
$.when(ajaxCall).then(function () {
if (bool) {
//debugger;
$.ajax({
type: "GET",
url: '#Url.Action("CreateEmailReport", "Service")',
contentType: "application/json; charset=utf-8;",
data: { "folderData": myJSON },
traditional: true,
})
}
});
});

Ajax Post method not working for user defined function

UpdateModule is a function used for update module details. It's not a view page.
When click on update, it returns 500 (internal server error) or 404 error
please help to fix it
$.ajax({
type: 'POST',
url: '#Url.Action("ETM_PRODUCTS","UpdateModule")',
//contentType: 'application/json',
datatype: JSON,
data: { 'ModuleID': ModuleID, 'ModuleName': ModuleName, 'ModuleDescription': ModuleDescription },
success: function (data) {
if (data == true) {
alert("Updated Successfully");
}
},
error: function (msg) {
alert("Error")
},
});
c#
public JsonResult UpdateModule(int ModuleID,string ModuleName,string ModuleDescription) {
bool status = true;
PROD_MODULE tabledata = db.PROD_MODULE.Where(x => x.ETM_MODULE_ID == ModuleID)
.FirstOrDefault();
tabledata.NAME = ModuleName;
tabledata.DESCRIPTION = ModuleDescription;
db.SaveChanges();
return Json ( status, JsonRequestBehavior.AllowGet );
}
There is a problem in the way you call Url.Action.
The first parameter is the action and the second the controller.
Here is the documentation : link

Cannot connect from client side to web method on asp.net

i'm trying to connect from html page to web method with ajax function
$.ajax({
url: "http://localhost:43599/WebForm1.aspx/GetWeatherResultsbyscript",
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
data:{Zip:input},
dataType: 'json',
success: function (data,result) {
alert(result.d);
},
error: function () { alert(" Server not found"); }
});
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
private object GetWeatherResultsbyscript(string Zip) {
ServiceReference1.ForecastReturn result = new ServiceReference1.ForecastReturn();
ServiceReference1.WeatherSoapClient client = new ServiceReference1.WeatherSoapClient();
result = client.GetCityForecastByZIP(Zip);
return (result);
}
As a result i'm getting that server is not found, but if i delete to rows in ajax function
contentType: "application/json; charset=utf-8",
dataType: "json",`
i'm getting 'undefined' as a result.
Can anyone tell what i did wrong in this implication of connection to web method?
The method should be public. Try the code below,
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public object GetWeatherResultsbyscript(string Zip) {
ServiceReference1.ForecastReturn result = new ServiceReference1.ForecastReturn();
ServiceReference1.WeatherSoapClient client = new ServiceReference1.WeatherSoapClient();
result = client.GetCityForecastByZIP(Zip);
return (result);
}
Also,
The application name is missing in the URL: http://localhost:43599/application name/WebForm1.aspx

asp.net MVC JavaScript call to controller

I'm currently working on an ASP.Net MVC project.
I have a JavaScript function which takes an XML string as input. I would like to send this to the controller.
I have done so using an AJAX request, but in the controller the string is null.
View:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")'
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: xml,
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Controller:
public ActionResult Save(string xml)
{
Console.WriteLine(xml);
W6ViewModel viewModel = new W6ViewModel();
viewModel.engineers = db.W6ENGINEERS.ToList();
viewModel.tasks = db.W6TASKS.ToList();
viewModel.skills = db.W6TASKS_REQUIRED_SKILLS1.ToList();
var engList = new List<object>();
foreach (var engineer in viewModel.engineers)
{
engList.Add(new { key = engineer.ID, label = engineer.Name });
}
ViewBag.engineers = engList;
return View("Index", viewModel);
}
var xml = scheduler.toXML()
alert(xml):
Error Code (Sorry, wall of text):
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.QueryString value was detected from the client (xmlString="<data><event>
Name your parameter like this:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")';
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: { xml: xml},
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Also put this tag above you controller action:
[ValidateInput(false)]
See the following ajax call:
$.ajax({
url: '#Url.Content("~/myaccount/CheckDuplicateEmailAddress")',
data: { "emailAddress": email },
async: false,
type: "post",
success: success,
error: error
});
And controller action is below. you need to send param as this:
data: { "emailAddress": email }
Remember case sensitivity and double quotes:
public bool CheckDuplicateEmailAddress(string emailAddress)
{
}

Categories

Resources