Web Api Error 500 - asp.net-web-api

I have got a ajax call through which I am calling my Web Api.My code is as follows-
function DataFrame() {
var abc = {};
abc.Country = countryName;
abc.Month = monthName;
abc.SampleData = selectedStores;
var datatoSend = JSON.stringify(abc);
jQuery.support.cors = true;
$.ajax({
url: URL + '/api/Sample/AddSampleToFrame/',
type: "Post",
data: JSON.stringify(datatoSend),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.length > 0) {
_sampletabledata = $.parseJSON(result);
PoplulateListSample();
PopulateSampleCheckBox();
BindSampleGrid();
BindBoxesWithSet();
}
}, //success of ajax
return false;
}
This code is returning error 500.Need your suggestions

Related

Returning error from controller to AJAX jQuery

I works with ASP.net MVC and I have get "Error" from belowe my JavaScript code:
This is my AJAX jQuery code:
$(document).ready(function () {
var dataId;
$(".item2 .small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').prop('href', url);
$.ajax({
url: '/Carpet/CheckCarpet',
type: 'POST',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success == false)
$('#dateLink').hide();
else
$('#dateLink').show();
alert("Success");
},
error: function (errorThrown) {
alert("Error");
}
});
and this is a controller code:
[HttpPost]
public ActionResult CheckCarpet(int CarpetImageid)
{
bool DecorShow = false;
DecorShow = db.Images.Where(x => x.Id == CarpetImageid).FirstOrDefault().DecorTest;
return Json(new JsonData { Success= DecorShow });
}
what's the reason? Someone knows?
I found the solution.i change url to #Url.Action("CheckCarpet", "Carpet") and fixed.
$(".small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').attr('href', url);
$.ajax({
url:'#Url.Action("CheckCarpet", "Carpet")',
type: 'Post',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.Success == false) {
$('#dateLink').hide();
$('.p2').hide();
}
else {
$('#dateLink').show();
$('.p2').show();
}
},
error: function (error) {
alert(error.d);
}
});
});

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

Parameter is not passing by ajax call

I have an ajax call to a function in my controller. I need to pass a parameter to that function but it is not happening. My ajax call:
$("#BTN_Plus").click(function () {
var CurrentPage = #Model.CurrentPage;
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify(CurrentPage),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
});
The function in my controller:
public PartialViewResult ListerIncidentsHotline( int page = 1)
{
int NextPage = 1 + page;
const int PageSize = 10;
int NumDossier = StructureData.DonneNumDossier((string)Session["Utilisateur"], (string)Session["MotDePasse"]);
IEnumerable<IncidentHotline> ListeIncidents = StructureData.DonneIncidentsHotline(NumDossier);
int NbreIncidents = StructureData.DonneNombreIncidents(NumDossier);
ViewBag.NombreIncidents = NbreIncidents;
var viewModel = new IncidentsPageInfo()
{
NumPages = (int)Math.Ceiling((double)ListeIncidents.Count() / PageSize),
CurrentPage = NextPage,
PageSize = PageSize,
Incidents = ListeIncidents.Skip((NextPage - 1) * PageSize).Take(PageSize),
};
return this.PartialView(viewModel);
}
When I make an alert of the variable CurrentPage, it shows me the right value, but when it comes to the ajax call, i get an error saying that the parameter is null. Can't figure out what's wrong with that.
well as a data you need to pass a numerable value with the name of page, change your ajax data
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify(CurrentPage),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
change data to data: {page: CurrentPage}
This is much easier....
$.get("/Accueil/ListerIncidentsHotline", { CurrentPage: #Model.CurrentPage } ).
done(function (data) {
$("#Affichage").html(data);
});
Obviously the problem came out of my ajax call. So I have to concatenate the name of the parameter with its value inside the method JSON.Stringify, as below:
$("#BTN_Plus").click(function () {
var CurrentPage = #Model.CurrentPage;
alert(CurrentPage);
$.ajax({
type: "POST",
url: "/Accueil/ListerIncidentsHotline",
data: JSON.stringify({ page: CurrentPage }),
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#Affichage").html(data);
}
});
});

retrieve the result of an ajax request as a variable

How can I get the result of my ajax post into a variable:
function decode_original(hshdecode) {
var decode_original = 'decode=1&hashvalue=kjh4k5hq35l&hashkey=12345';
$.ajax({
type: "POST",
async: false,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
url: 'decode_function.php',
data: decode_original,
cache: false,
success: function(return_value) {
var decoded_value = return_value;
console.log("Decoded Value:" +decoded_value);
return decoded_value;
},
error: function(data){
return data;
}
});
}
The above actually gets the return value successfully, but I am unable to pass the result into a variable:
var decode_value = decode_original(encoded_value);
alert(decode_value);
use responseText like :
success: function(return_value) {
var decoded_value = return_value.responseText;
console.log("Decoded Value:" +decoded_value);
return decoded_value;
}

Send JSON string to a C# method

In my ASP.NET page I have the following method:
public static void UpdatePage(string accessCode, string newURL)
{
HttpContext.Current.Cache[accessCode] = newURL;
}
It actually should receive the accessCode and newURL and update the Cache accordingly. I want to pass the values to that method from JavaScript, using an AJAX request. The code for it is as follows:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var dataToSend = [ {accessCode: code, newURL: url} ];
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {"items":dataToSend},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However this doesn't seem to work. Could anybody help me figure out where the bug is?
UpdatePage is a void method that doesn't return anything, so there is nothing to look at in the response.
You could look at the HTTP return code and check that it was 200 OK or you could modify the web method:
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result
}
Edit:
It looks like your JSON arguments to the WebMethod are incorrect, you don't need the "items" in your JSON. The arguments should match your webmethod exactly.
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}

Resources