MVC method call working in Fiddler, but not in browser - c#

I am able to get a result back from a method call in Fiddler using the below syntax:
http://localhost:1196/Home/GetSpecificFuelTicketAsync/6460194
Note that as going through Fiddler, my controller breakpoints are hit and I can see where it returns a value coming out of the method.
However, I am not able to get a result back when running from my browser. When it tries to execute the ajax method, the "success" function does not fire and skips to the "error" function where it says it can't find the record.
What am I doing wrong with my ajax call? There is something I am definitely doing wrong in my ajax call. I have verified during debugging, that the variable "ticketNbr" actually contains a value.
Here is my ajax call:
$.ajax({
url: "Home/GetSpecificFuelTicketAsync",
data: "{id:" + ticketNbr + "}",
type: "POST",
dataType: "json",
success: function (data) {
DisplayReceipt(data);
},
error: function () {
alert("No record found for ticket " + ticketNbr);
}
});
Here is my Route.config file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Here is my controller method:
[HttpPost]
public async Task<JsonResult> GetSpecificFuelTicketAsync(int id)
{
try
{
string imageID = await db.GetSpecificFuelTicketAsync(id);
return Json(imageID, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
strRemedyTktResponse = IssueRemedyTicket("Class: FuelTktController" + CrLf + "Method: GetSpecificFuelTicket" + CrLf + "Error: " + ex.Message + CrLf + "InnerException: " + ex.InnerException + CrLf + "Source: " + ex.Source + CrLf + "StackTrace: " + ex.StackTrace);
LogMessage.WriteEventLog("Class: FuelTktController" + CrLf + "Method: GetSpecificFuelTicket" + CrLf + "Error: " + ex.Message + CrLf + "InnerException: " + ex.InnerException + CrLf + "Source: " + ex.Source + CrLf + "StackTrace: " + ex.StackTrace, "FuelTktController", 1, strRemedyTktResponse);
return null;
}
}

I think it might just be the way you are defining your ajax call.. try this
$.ajax({
url: '#Url.Action("GetSpecificFuelTicketAsync")',
data: "{'id': '" + ticketNbr + "'}",
type: "POST",
contentType: 'application/json; charset=utf-8',
success: function (data) {
DisplayReceipt(data);
},
error: function () {
alert("No record found for ticket " + ticketNbr);
}
});

Change this line -
data: "{id:" + ticketNbr + "}",
to this -
data: "id=" + ticketNbr,
or this -
data : {id: ticketNbr} //loose the quotations.
and try again.
With this controller method the next one is even better option -
$.ajax({
url: "Home/GetSpecificFuelTicketAsync/" + ticketNbr,
type: "POST",
dataType: "json",
success: function (data) {
DisplayReceipt(data);
},
error: function () {
alert("No record found for ticket " + ticketNbr);
}
});

Related

Catch is returning a custom error page and not the error message

I am calling a controller with Ajax Post, In the controller, catch is returning a custom error page, instead of returning the error message.
Catch Controller:
catch (Exception ex)
{
return BadRequest(ex.Message + " - " + ex.InnerException?.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
}
Post Ajax:
$.post({
url: eapi + 'pedido/' + id_empresa + '/' + token_emp + '/' + agendamentotf,
data: JSON.stringify(vm.ped_post),
headers: {
"Content-Type": "application/json"
},
success: function(data) {
var response = data;
},
error: function(error) {
console.log(error.responseText);
}
});
This error.responseText is returning an error page and not the error message.
Can someone help?
Im not an expert in jquery's post, but i've found that you dont enter the error function where you do, but this way:
$.post({
url: eapi + 'pedido/' + id_empresa + '/' + token_emp + '/' + agendamentotf,
data: JSON.stringify(vm.ped_post),
headers: {
"Content-Type": "application/json"
},
success: function(data) {
var response = data;
}
})
.fail((xhr, status, error) => {
console.log(error.responseText);
});
you can see it here
The error is that you are trying to use $.post instead of $.ajax
Here is your corrected code:
$.ajax({
type: "POST",
url: eapi + 'pedido/' + id_empresa + '/' + token_emp + '/' + agendamentotf,
data: JSON.stringify(vm.ped_post),
headers: {
"Content-Type": "application/json"
},
success: function(data) {
var response = data;
},
error: function(XMLHttpRequest, textStatus, error) {
console.log(error);
}
});
Sounds like your controller isn't configured as an API controller, in which case you might need to change your action return type to JsonResult.
Try use a simple string in the BadRequest, like return BadRequest("Test");
I suspect this code may throw another exception.
ex.Message + " - " + ex.InnerException?.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace

jqplot - pass variable via ajax to C# page

I am unable to retrieve values passed by $.ajax on my c# page.
I am using jqplot and I want to pass two pieces of information. One is stored in a hidden field called 'hidden_plateid' and the second piece of information is from a dropdown box called 'SampleNumberList'
This is the hidden field
<input type="text" name="hidden_plateID" id="hidden_plateID" hidden="hidden" runat="server" />
And this is the drop down box:
<select name="SampleNumberList" class="DropDownBox_editjob" id="SampleNumberList">
<option value="--SELECT--"></option>
<option value="001r">001r</option>
<option value="002r">002r</option>
</select>
I simply then say that everytime, someone selects from the dropdown box, to get and get the information from the db and plot the graph
$('#SampleNumberList').on('change', function (e) {
var ajaxDataRenderer = function (url, plot, options) {
var ret = null;
$.ajax({
data: {
PlateID2: options.PlateID,
SampleID2: options.SampleID,
},
async: false,
url: url,
dataType: "json",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
return ret
};
var jsonurl = "SpectraData.aspx";
var plot2 = $.jqplot('chartdiv', jsonurl, {
title: "AMIRA",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl, PlateID: $('#hidden_plateID').val(), SampleID: $('#SampleNumberList').val()
}
});
});
I use Request.Querystring to try and retrieve the value in the c# file but so far, I get nothing
if (Request.QueryString["PlateID2"] != null)
{
PlateID = Request.QueryString["PlateID2"].ToString();
}
if (Request.QueryString["SampleID2"] != null)
{
SampleID = Request.QueryString["SampleID2"].ToString();
}
You are trying to retrieve values from a query string , yet you are passing the parameters as json.
In order to retrieve them as a query string params, you need to pass them along your url.
$.ajax({
async: false,
url: url + "?PlateID2=" + options.PlateID + "&SampleID2=" + options.SampleID + "",
dataType: "json",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
In reality, the right way to do this is to pass params as a json string and intercept in the code behind.
$.ajax({
url: url/Somemethod,
type: 'POST',
dataType: 'json',
data: "{'PlateID2':'" + options.PlateID + "','SampleID2':'" + options.SampleID + "'}",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
In your codebehind :
[WebMethod]
public static void Somemethod(string PlateID2,string SampleID2)
{
}

jQuery UI autocomplete error via Web Service/JSON response

I've been trying to get this to work for a few hours now but can't see where I'm going wrong.
I've been checking Firebug for the server response and it retrieves the json data via .asmx web service fine. The only error i have to go off is the one in firebug that's triggered when 2 or more characters are typed in:
TypeError: c.settings[d].call is not a function
jQuery Code Snippet:
$(document).ready(function () {
$("#<%= txtCustomer.ClientID %>").autocomplete({
minLength: 2,
async: true,
source: function(request, response) {
$.ajax({
url: "../Services/AJAXHandler.asmx/GetCustomers",
data: "{'filter':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function(item) {
return {
label: item.customerName
};
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + XMLHttpRequest.statusText + " : " + XMLHttpRequest.status;
if (XMLHttpRequest.status != "0" || errorThrown != "abort")
{
alert(errorMessage);
}
}
});
}
});
If anybody could point me in the right direction that would be brilliant.

JSON syntax in C#

I have written the following Javascript but get the error 'Invalid JSON primitive: strSeason'. The rest of the syntax seems fine but I can't seem to get the 'data' parameter right. Can anybody help me with the syntax?
TagBuilder script = new TagBuilder("script");
script.Attributes.Add("type", "text/javascript");
script.Attributes.Add("language", "javascript");
// ReSharper disable LocalizableElement
script.InnerHtml = #"
$.ajax({
type: 'POST',
async: true,
contentType: 'application/json; charset=utf-8',
dataType: 'html',
url: '/en-US/" + areaName + '/' + controllerName + '/' + actionName + #"',
data: " + "{strSeason:'" + season + "', strTeam:'" + team + #"'},
beforeSend: function(xhr){
$(this).addClass('ajaxRefreshing');
xhr.setRequestHeader('X-Client', 'jQuery');
},
success: function(html){
$(this).html(html);
},
complete: function(){
$(this).removeClass('ajaxRefreshing');
}
});
";
wrap the names in quotes
data: " + "{'strSeason':'" + season + "', 'strTeam':'" + team + #"'},
EDIT: You may just need to send the JSON string so wrap entire string in quotes.
data: " + "\"{'strSeason':'" + season + "', 'strTeam':'" + team + "'}\"" +#",

Passing parameter to controller function from jQuery function '$.ajax'

I am using ASPNET MVC 2.0. I'm trying to pass a value from View to Controller function using jquery function .ajax. My jquery function is:
$(document).ready(function() {
$("#Search").click(function(event) {
var searchString = $("#TraderSearch").val();
$.ajax({
type: 'POST',
url: '/Build/SearchTrader',
data: "{strData : '" + searchString + "' }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(ResultList) {
var contents = "";
var count = 0;
$(ResultList).each(function() {
contents = contents + '<tr><td>' + ResultList[count].Name + '</td><td>' + ResultList[count].Value +
'</td><td><a class="edit"><img src="../../html/images/Edit.gif" width="14" height="14" alt="edit" /></a></td></tr>';
count = count + 1;
});
$("#SerachResultList").append(contents);
alert("{strData : '" + searchString + "' }");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + "\n" + errorThrown);
}
});
});
});
And my Controller function is as follows:
public ActionResult SearchTrader(string strData)
{
//Function to search DB based on the string passed
return Json(lstDictObject);
}
My problem is that, I am not able to get the value in my controller. I'm getting strData as 'null'. I think there is somme mistake in the way i'm trying to pass the value? Can anyone correct me?
Thanks in Advance,
Vipin Menon
try this:
data: "strData = " + searchstring
I believe the following should work:
data: { strData: searchstring }
Quotes caused the same issue in the script I just tested.
You also need to check the spelling on your "#SerachResultList" if this is your actual code.

Categories