Display NO Data when Ajax success is empty or null - c#

I have a WebMethod, which is populating a JQuery DataTable with some initial values. I have a drop down list, which calls the WebMethod and try to populate it with different values. My problem, is if the JSON data is null (or '') then i get JSON.parse: unexpected end of data.
Now, I can check the length of the object using if(msg.d.length !- '' { build the table} ) However, if the length is null (''), then i never go into the build table, and therefore cant present that there is no data / no records.
How can I ensure that if the JSON string/object is null ('') that DataTables still presents No Records found etc...?
$('#ddBICS').change(function (e) {
var val = $('#dd option:selected').text();
msgDateDetail(val);
});
function msgDateDetail(value) {
$.ajax({
type: "POST",
url: "Default.aspx/MsgDateDetail",
cache: false,
data: JSON.stringify({ searchValue: value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = JSON.parse(msg.d);
var asInitVals = new Array();
otblMsgDateDetail = $("#tblMsgDateDetail").dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aaData": data
})
}
});
}

msg could be null or undefined, just checking for the variable will tell you that. Also since you're using JQuery you could check if d is an array with the isArray JQuery method.
if(msg && msg.d && $.isArray(msg.d) && msg.d.length > 0) {
// build the table
}else{
// data is empty
}
Within your above method you would do the following.
function msgDateDetail(value) {
$('#tblMsgDate
$.ajax({
type: "POST",
url: "Default.aspx/MsgDateDetail",
cache: false,
data: JSON.stringify({ searchValue: value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var asInitVals = new Array();
var data = (msg && msg.d && $.isArray(msg.d))? msg.d : new Array();
otblMsgDateDetail = $("#tblMsgDateDetail").dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aaData": data
})
}
});
}
The documentation for the jquery method is located on jquery.com http://api.jquery.com/jQuery.isArray/
For this to work make sure that your Default.aspx/MsgDateDetail returns application/json for the content type. To do this in the aspx file you do the following:
Response.ContentType = "application/json"
You must do this before you do any Response.Write

You should the length like this
if(msg.d.length !=0) { // Try this
//-- build the table
}

Related

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

Getting a null value in IActionResult when passed with AJAX

I'm trying to make an AJAX Request to a method of iActionResult in my ASP.NET application. The request is getting to the method but when its passed along it has a value of null in my method. The value of selectedKommun is always a number when I check it in the console.
$(document).ready(function () {
$('#kommun').change(function () {
var selectedKommun = $("#kommun").val();
var fordonSelect = $('#fordon');
fordonSelect.empty();
if (selectedKommun != null && selectedKommun != '') {
$.ajax({
type: "POST",
url: "/avboka?handler=GetFordon",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "Id": selectedKommun },
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data);
})
}
});
});
Here is my method where im sending my request. I have commended out some code just to check the value of Id.
[HttpPost]
public IActionResult OnPostGetFordon(int Id)
{
//if (!string.IsNullOrWhiteSpace(kommunFordonId) && kommunFordonId.Length == 3)
//{
// IEnumerable<SelectListItem> regions = _fordonRepo.GetFordon(kommunFordonId);
// var json = JsonConvert.SerializeObject(regions);
// return this.Content(json);
//}
//return null;
return new JsonResult(Id);
}
Instead of
contentType: "application/json; charset=utf-8",
try
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
This is because you are not sending JSON content, only an int.
You also don't really need to specify a datatype since you are only sending an int.

How to pass a model with extra unbound parameter from the view to the controller via ajax [duplicate]

I have been trying to post two parameteres...
This is the ajax code
function Kaydet() {
var params = {};
var Kiralayan = $("#RentForm").serialize();
params.kisi = Kiralayan ;
params.aracid = P.AracID;
console.log(params);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: params,
dataType: "text",
success: function (response) {
if (response != "OK") {
alert("Kayıt yapılamadı.");
}
else {
document.getElementById("RentForm").reset();
alert("Kayıt başarıyla gerçekleştirildi.");
$("#myModal").modal('hide');
Ara();
}
}
});
Method
public ActionResult Save(Kiralayan kisi = null, int aracid = 0)
{
the problem is ajax posts "aracid" corretly but "kisi" turns null when the method is trigged...
I tried not to post "aracid" with "kisi" so ajax posted well for one parameter "kisi", but doesnt work together...
If you serializing the form, then you can add additional values to it with the .param() function
var data = $("#RentForm").serialize() + '&' + $.param({ 'aracid': AracID }, true);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: data,
....
MVC will map the object for you, so you might as well skip the extract nesting of the form within the object.
Notes:
If aracid is also a property in the model, it will map to both the property and the extra parameter.
Using push on the serialise() collection is more maintainable than the alternative of concatenating strings before the serialize() call.
e.g.
var Kiralayan = $("#RentForm").serialize();
// Add the extra non-form parameter
Kiralayan.push({name: 'aracid', value: P.AracID});
Full example:
function Kaydet() {
var Kiralayan = $("#RentForm").serialize();
// Add the extra non-form parameter
Kiralayan.push({name: 'aracid', value: P.AracID});
console.log(params);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: Kiralayan,
dataType: "text",
success: function (response) {
if (response != "OK") {
alert("Kayıt yapılamadı.");
}
else {
document.getElementById("RentForm").reset();
alert("Kayıt başarıyla gerçekleştirildi.");
$("#myModal").modal('hide');
Ara();
}
}
});

Passing multiple AJAX call data parameters to MVC controller goes wrong? [duplicate]

I have been trying to post two parameteres...
This is the ajax code
function Kaydet() {
var params = {};
var Kiralayan = $("#RentForm").serialize();
params.kisi = Kiralayan ;
params.aracid = P.AracID;
console.log(params);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: params,
dataType: "text",
success: function (response) {
if (response != "OK") {
alert("Kayıt yapılamadı.");
}
else {
document.getElementById("RentForm").reset();
alert("Kayıt başarıyla gerçekleştirildi.");
$("#myModal").modal('hide');
Ara();
}
}
});
Method
public ActionResult Save(Kiralayan kisi = null, int aracid = 0)
{
the problem is ajax posts "aracid" corretly but "kisi" turns null when the method is trigged...
I tried not to post "aracid" with "kisi" so ajax posted well for one parameter "kisi", but doesnt work together...
If you serializing the form, then you can add additional values to it with the .param() function
var data = $("#RentForm").serialize() + '&' + $.param({ 'aracid': AracID }, true);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: data,
....
MVC will map the object for you, so you might as well skip the extract nesting of the form within the object.
Notes:
If aracid is also a property in the model, it will map to both the property and the extra parameter.
Using push on the serialise() collection is more maintainable than the alternative of concatenating strings before the serialize() call.
e.g.
var Kiralayan = $("#RentForm").serialize();
// Add the extra non-form parameter
Kiralayan.push({name: 'aracid', value: P.AracID});
Full example:
function Kaydet() {
var Kiralayan = $("#RentForm").serialize();
// Add the extra non-form parameter
Kiralayan.push({name: 'aracid', value: P.AracID});
console.log(params);
$.ajax({
type: "POST",
url: '#Url.Action("Save","AracKirala")',
data: Kiralayan,
dataType: "text",
success: function (response) {
if (response != "OK") {
alert("Kayıt yapılamadı.");
}
else {
document.getElementById("RentForm").reset();
alert("Kayıt başarıyla gerçekleştirildi.");
$("#myModal").modal('hide');
Ara();
}
}
});

JSON data html parameter

why JSON doesn't work with html text (var text_html = '<p></p><t></t>'; ) but this will be work correct (var text_html = 'example';)
doesn't work
var text_html = JSON.parse('<p></p><t></t>');
Problem:
function Save() {
var text_html = '<p></p><t></t>';
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
My_Text: text_html
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
public JsonResult DodajTematSave(string My_Text)
{
return Json(new { Success = true});
}
also this doesn`t work
var dom_string = '<div>xxx<div>yyy</div></div>';
var text_html = dom_string.innerText();
also this doesn`t work
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
try this:
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
and use ajaxSetup to instruct JQuery how to handle the data type
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Because those are escaping characters in JSON. You will have to parse html in a way to make it JSON friendly if you wanted it passed through JSON.
For this people who have problem with this I can show another way to fix this problem but very ugly click here

Categories

Resources