How to pass parameter from Ajax to C# using header request? - c#

I have the following request:
var response = $.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: this.AgentServiceUrl + "/" + methodName,
data: data,
async: this.Async,
success: function (xml, textStatus) { if (successHandler != null) successHandler(state, $.xml2json(xml), textStatus); },
error: function (xmlHttpRequest, textStatus, errorThrown) { if (errorHandler != null) errorHandler(state, xmlHttpRequest, textStatus, errorThrown); }
});
I want to add to a variable to this request header and consume it on C#,
I try many ways but I can't consume it on C#:
beforeSend: function (req)
{
req.setRequestHeader("AgentGUID", this.AgentGUID);
},
Pass parameters:
Can you help me? I don't want to change the function at the C# part I just want to use something like:
(System.Web.HttpContext.Current.Request.Headers["someHeader"]

Your beforeSend should work as you wish, but the reason you are not getting the value on server side is that this.AgentGUID on this method call is undefined because this in that context is pointing to another object (most probably ajax request object).
By defining a variable outside your ajax call you issue will be fixed.
var me = this;
var response = $.ajax({
...
beforeSend: function (req)
{
req.setRequestHeader("AgentGUID", me.AgentGUID);
},
...
});

Related

Parameter null in C# code but it is set in AJAX call

I'm developing an ASP.NET MVC 5 application with C#, .NET Framework 4.7 and jQuery 1.11.2.
This javascript code:
function RequestCodes(button, poId) {
var URL = '/ProductionOrder/RequestCodeForIncompleteOrder';
//button.attr("disabled", "disabled");
$('#ok').hide();
$('#fail').hide();
$('#cargando').show();
$.ajax({
url: URL,
type: "PUT",
dataType: "HTML",
data: { productionOrderId: poId },
contentType: "json",
success: function () {
$('#cargando').hide();
$('#ok').show();
$("#ok").fadeOut("slow", function () {
$('#ok').hide();
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
$('#cargando').hide();
$('#fail').show();
$("#fail").fadeOut("slow", function () {
$('#fail').hide();
//button.removeAttr("disabled");
});
}
});
}
Throws this error:
he parameters dictionary contains a null entry for parameter
'productionOrderId' of non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult RequestCodeForIncompleteOrder(Int32)' in
'TRZF.Web.API.Controllers.ProductionOrderController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter.Parameter name: parameters.
When I call the method:
public ActionResult RequestCodeForIncompleteOrder(int productionOrderId)
The problem is with the parameter name in the javascript code, but I don't know how why because it has the same name like in the C# code.
How can I fix this error?
Here is the solution:
you have syntax error at below line. I have fixed this.
data: "{'productionOrderId':'" + poId + "'}",
I have found the problem.
$.ajax({
url: URL,
type: "PUT",
data: { productionOrderId: poId },
success: function () {
$('#cargando').hide();
$('#ok').show();
$("#ok").fadeOut("slow", function () {
$('#ok').hide();
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
$('#cargando').hide();
$('#fail').show();
$("#fail").fadeOut("slow", function () {
$('#fail').hide();
//button.removeAttr("disabled");
});
}
});
I have removed dataType: "HTML", and contentType: "json",, and now it works.
I have done another test, removing only contentType: "json", and it works. So, I think the problem is with setting the contentType.
at controller RequestCodeForIncompleteOrder function you need to get productionOrderId with nullable data type like following :
RequestCodeForIncompleteOrder(int? productionOrderId)
{
//your code here
}
? mean accept nullable data type
changing the content type to "application/json" and strigifying the data fixed the issue for me.
here is the sample code.
$.ajax({
url: "/Home/RequestCodeForIncompleteOrder",
type: "POST",
dataType: "json",
data: JSON.stringify({
productionOrderId: 1
}),
contentType: "application/json",//change "json" to "application/json"
success: function () {
console.log("success");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
First of, is your route to the api correct?
Usually it's prefixed with api/..
Secondly, the client model that you are sending to the server is not matching the expected value type (int) on the server side.
Option 1 is to match the server side with the client side object.
Your client object { productionOrderId: poId } is equal to a server side model defined as this
public class RequestModel
{
public int productionOrderId { get; set; }
}
Use the model in the api controller method and read it from the body
public ActionResult RequestCodeForIncompleteOrder([FromBody]RequestModel model){}
NOTE: Don't forget to stringify the object before sending it in the client when using content type application/json, data: JSON.stringify({ productionOrderId: })
Option 2 is to send the productionOrderId in the route
[RoutePrefix("api/ProductionOrder")]
public class ProductionOrder : ApiController
{
[HttpPut]
[Route("RequestCodeForIncompleteOrder/{productionOrderId}")]
public ActionResult RequestCodeForIncompleteOrder(int productionOrderId){}
}
Then call this method by using url api/ProductionOrder/RequestCodeForIncompleteOrder/2345 where 2345 is your order id

no data is received from an ajax call

$.ajax({
type: "GET",
contentType: "text/html; charset=utf-8",
url: "secret.aspx",
data: {
plu: $("#Text1").val(),
gh: $("#TextBox1").val(),
sid: $("#TextBox2").val()
},
dataType: "html",
success: function(data) {
$("#result").html(data);
}
});
I am making a call to the aspx page, the call goes correctly. Data is entered in database, but values are not returned to the page
The return statements are as follows:
Response.Write("hello");
Response.End();
It should work. Perhaps an error's occurring with secret.aspx. To find out, add an error setting to the ajax call so you get to know about any errors. You could also add an alert to display the returned data, in case it's something to do with your result element:
success: function (data) {
alert(data);
$("#result").html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' - ' + xhr.responseText);
alert(thrownError);
}
});

How to read json response as name value pairs in JQuery ajax

I want to read json response as name and value pairs in my JQuery code. Here is my sample JSON response that I return from my dotnet code:
const string format = "\"HasCases\": \"{0}\"";
StringBuilder json = new StringBuilder(128);
json.Append("{");
json.AppendFormat(format, JSONString("true"));
json.Append("}");
Response.Clear();
Response.AppendHeader("Content-type", "application/json; charset=utf-8"); Response.Write(json.ToString());
Response.End();
To get Json value ,is it necessary to use Response code?In my Json page , I am able to get the output as HasCases : true.
Here is my JQuery code
<span id="testSpan" runat="server">inactive</span>
<script type="text/javascript">
inactive
$.ajax({
type: 'POST',
url: "~/Pages/UserCaselistnonEmptyAjax.aspx",
dataType: "json",
success: function (response){
$('#testSpan').innerHTML = response.HasCases;
},
error: function (e1, e2, e3) {
$('#testSpan').innerHTML = 'Error';
}
});
</Script>
When I am debugging form firebug My control does not going to "$('#testSpan').innerHTML = response.HasCases; ".It is coming out from the loop.
jQuery objects don't implement .innerHTML. Use .html() instead:
$('#testSpan').html(response.HasCases);
I am returning my json using
return (new JavaScriptSerializer().Serialize(request));
in my c# code.and I am calling the function returning this value at page load event.
and the output is this
{"registration_ids":["1","2"],"data":{"message":"Your message","tickerText":"Your ticker","contentTitle":"Your content"}}
but I am unable to read this returned json fomrat with jquery ajax
my ajax is below
function as()
{
$.ajax({
type:"get",
url:"mydjson.aspx",
contentType: 'application/json;charset=utf-8',
dataType: {'json':'datas'},
//data: JSON.stringify(request),//{ get_param: 'value' },
success:function (msg) {
$("#table").html("<h1>" + msg+ "</h1>").fadeIn("slow");
},
// function (data, status)
error: function (xhr, textStatus, error)
{
var errorMessage = error || xhr.statusText;
$("#table").html("<h3>" + errorMessage + "</h3>").fadeIn("slow");
}
});
return false;
// });
}
I am getting the error "Ivalid json" plus the content of page" mydjson.aspx".help me for this.

Http compatible dealing with data transmission and error handling using jquery ajax requests

I'm wondering how should look the correct way of dealing with data transmission and handling errors using latest jquery ajax requests with http compatible approach.
I've noticed, that when unhandled exception occurs at server side, and I did not specify the data type I'm expecting in http protocol, the success method invokes and the client receives 200 OK response, as if nothing wrong happend:
$.ajax({
url: action,
type: 'POST',
data: jsondata,
success: function (data, textStatus, xhr) {
// i'm here now
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
If I specify type, that I'm expecting for exaple json, an ajax error function invokes. It's because stack trace is not serialized by default to json, so parsing will fail:
$.ajax({
url: action,
type: 'POST',
dataType: 'json',
data: jsondata,
contentType: 'application/json; charset=utf-8',
success: function (data, textStatus, xhr) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// but now I'm here
}
});
Now it's also 200 OK, but an error (not success) is invoked.
What is the better way to cope with exception handling. Should I specify the type, which is more RESTFull in my opinion, or just let it be unspecified, and always jump into success ?
Should I always wrap ajax method at the server side in try{}catch(){} block, and pass error of appropriate type, the client asks me to return ?
[HttpPost]
public NJsonResult Execute()
{
try
{
// do some logic if you do not mind
if (success)
{
return new NJsonResult(new {status = "success"});
}
return new NJsonResult(new { status = "error" });
}
catch(Exception e)
{
return new NJsonResult(new { status = "error" });
}
}
$.ajax({
type: 'POST',
url: action,
dataType: 'json',
data: jsondata,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status == "success") {
}
else (data.status == "error") {
}
}
Mabye should I always care of predictable errors and don't care about exceptions, and did not specify any type ?
[HttpPost]
public NJsonResult Execute()
{
// do some logic if you do not mind
if (success)
{
return new NJsonResult(new {status = "success"});
}
return new NJsonResult(new { status = "error" });
}
$.ajax({
type: 'POST',
url: action,
data: data,
success: function (data) {
if (data.status == "success") {
}
else {
// handle even exceptions, because content-type in not specified
}
}
});
Where is the place for error function and correct http status codes (not always 200 OK)
Now, I've implemented a global hook for intercepting unhandled exceptions:
$(document).ready(function () {
$.ajaxSetup({
error: function (XMLHttpRequest, textStatus, errorThrown) {
// handle it if you dare
}
});
});
and always specify the content-type and accept headers, using contentType and dataType ajax properties. I do not use try{}catch{} block - I don't care about logic abnormal behavior. I just log it in Global.asax and pass it further to the response.
So, as in the first lines of this question, what is the best approach ? Any other ideas ?

unable to pass post value over from ajax to the page in .net c#

Does anyone know what is it going on here? I have try to pass a value from ajax to .aspx, but somehow the value seem doesn't pass over successfully.
Following is my code:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: "sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
and this is my code inside my .net c#:
newTest.Value = Request.QueryString["sState"];
Somehow the for Request.QueryString["sState"] is empty in .net c#. Does anyone know what is going wrong here ?
When passing data in POST, the data is not passed in Request.QueryString, it's passed into Request.Form instead. Try
newTest.Value = Request.Form["sState"];
Another thing I'd change is the jQuery call - use a data object instead of just a string, a such:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: { sState: "VIC" },
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Request.QueryString is for GET requests only. For POST requests, you need Request.Form. See also: Get POST data in C#/ASP.NET
You need to use GET request as it is light in nature but less secured too and it is passed in querystring.:
$.ajax({
type: "GET",
url: "pgtest.aspx?sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Now you will get below values:
newTest.Value = Request.QueryString["sState"];

Categories