jQuery POST passing null string on server (ASP.NET) - c#

I have an ASP.NET application sending data through AJAX to a handler withing my application. This works as it should when debugging locally, but as soon as I deploy the solution to the server, the handler only receives an empty string. I tried fiddling around with contentType and dataType, but without luck.
Here is my code so far.
aspx of the sending page, while "myData" is a simple string:
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: myData,
// tried all those content/dataTypes without any luck
//contentType: "text/plain",
//dataType: "text",
//contentType: "application/json; charset=utf-8",
//dataType: "json",
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
.ashx.cs of the receiving handler:
public void ProcessRequest(HttpContext context) {
//string data = new StreamReader(context.Request.InputStream).ReadToEnd();
var data = String.Empty;
context.Request.InputStream.Position = 0;
using(var inputStream = new StreamReader(context.Request.InputStream)) {
data = inputStream.ReadToEnd();
}
if (data != "") {
// doing something with my data here.
// this is never reached while on the server, but works fine locally!
} else {
context.Response.Write("Please supply data to the risk group service!");
}
}
public bool IsReusable {
get {
return false;
}
}
}
The data variable in the .ashx.cs file is filled when debugging locally, but always "" on the server. I have no clue why.

var para={};
para.myData="abcd"
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: para,
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
from server side
string myData=contect.Request.Form["myData"].toString();

Easy, just took me ~20 hours to figure out. Found the answer here: Web service returns "301 error moved permanently" in production environment
In short, I created a blank page within my project to ensure no plugins etc were interfering with the jQuery execution. Further, I created a very simple mask to submit certain data to the handler URL. Within this mask I varied different ways to POST data, when I tried implementing the POST as a [WebMethod] I finally got a clue, as the response was "301 moved permanently" from the WebMethod. Therefore I could start investigating and found out that my server was lowercasing the urls, obviously jQuery/HTTP does not like that.
I hope this post helps others struggling with similar problems.

Related

HttpContext.Request.Form.Keys is empty when HttpContext.Request.HasFormContentType = true

This was working 2 days ago and now it's not and I cannot figure out why. I am submitting form data via ajax:
var mData = 'item=' + itemid + '&action=' + action;
$.ajax({
url: "/Admin/Home/Ajax",
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: mData,
success: function (data) {
//Do Something
}
});
I have a method that process the incoming post:
if (HttpContext != null && HttpContext.Request.HasFormContentType)
{
foreach (var key in HttpContext.Request.Form.Keys)
{
QueryParams.Add(key, HttpContext.Request.Form[key]);
}
}
When the data is posted, HttpContext.Request.HasFormContentType is equal to true however, HttpContext.Request.Form.Keys.Count is equal to 0
I get no errors or anything. Any help or insight as to what is going on would be greatly appreciated.
This is a dotnet core 2.2 mvc web app.
Here is a working demo like below:
1.View:
<script>
var mData = 'item=' + 1 + '&action=' + "aaa";
$.ajax({
url: "/Home/Ajax",
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: mData,
success: function (data) {
//Do Something
}
});
</script>
2.Action:
[HttpPost]
public void Ajax(int item,string action)
{
if (HttpContext != null && HttpContext.Request.HasFormContentType)
{
foreach (var key in HttpContext.Request.Form.Keys)
{
}
}
}
3.Result:
You are sending query data, not form data. Try sending it in a form like:
{
item: ...,
action: ...
}
Edit: Actually I was a bit surprised that it works while sending raw type of data and then passing in the query-like string. But the mearly fact that it works it doesn't mean it is a proper way of doing things. Foe example if You try to send API request from Postman (which I tried to reproduce Your error) I wasn't even able to perofrm such a thing as Postman asked me for key value pairs and interpreted a given query as a one key. Besides sending js object is more simpler that building a string.
I was also facing the issue of HttpContext.Request.Form.Keys is empty.
I just removed the .aspx extension from the request page and now the problem seems to be resolved for me.

jquery Ajax responsetext "There was an error processing the request"

I am getting this error "There was an error processing the request" in the UAT environment. In my local, the code seems to be working fine.
This line Utility.WriteLogEvent("TestService", strMessage); is writing directly to db. Either way if this line fails or not, I should still be able to recieve a message coming from the server since it is properly handled.
But since I don't receive any response from the server, that means my webmethod is not reachable.
Given that the code below works, is there anything that I need to set in the web.config to make this work? Or anywhere I can start inspecting on the IIS that could give me some clues?
Thanks.
$('#lnkTest').click(function () {
alert('Click event is firing!');
$.ajax({
type: "POST",
url: "/_layouts/ServiceForm.aspx/TestService",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.d && response.d.length > 0) {
alert(response.d);
}
},
error: function (xhr, err) {
alert('responseText:' + xhr.responseText);
}
});
});
Here is my c# web method
[WebMethod]
public static string TestService()
{
string strMessage = string.Empty;
try
{
strMessage = "The service is running.";
Utility.WriteLogEvent("TestService", strMessage);
}
catch (Exception ex)
{
strMessage = "TestService fail.";
}
return strMessage;
}
For others who might come across the same error while calling a WebMethod with parameters.
Ensure that none of the arguments are empty as that also throws the same error without a proper reason. Provide a solution to prevent empty arguments from being passed to the Method on the client side. Perhaps an if statement.
I have resolved the issue. This is due to a dll deployed in the application server and it was blocked by the installed antivirus.

Server result to webpage

I am trying to simply write out some data to my webpage as a result of a callback. Everything works up until the point where I need to output the result of the callback.
Client-side:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}
Server-Side: (on page load)
//holds actions from page
string payload = HttpContext.Current.Request.Form["payload"] ?? String.Empty;
// See if there were hidden requests (callbacks)
if (!String.IsNullOrEmpty(payload))
{
string temp_AggregationId = CurrentMode.Aggregation;
string[] temp_AggregationList = temp_AggregationId.Split(' ');
Perform_Aggregation_Search(temp_AggregationList, true, Tracer);
}
else
{
HttpContext.Current.Session["SearchResultsJSON"] = "";
}
The rest of the server-side code works properly and just handles the parsing of the incoming and performs a search of the db and then parses the search results into a JSON obj.
Currently, the only way the json obj gets written to the page is if I call it without the callback (just call it on page load). Also, in firebug, it looks like the entire page source is posting back as the 'result' of the callback. I do see my json result within the posted back 'result' but it also contains the entire page HTML.
Moreover, I can't seem to get the result to post to the page which is the whole point. Actually, I could get the result to post to the page by simply uncommenting that bit in the client side code but it posts a copy of my site and not the actual result I thought I created...
What am I missing? How do you explicitly state in the C# code what is returned to the JS callback as 'result'?
You get the entire page because you're making a request to an ASP.NET page. In fact, you're requesting the vary same page you're viewing. The server is returning what it would return if you were submitting a form.
To get JSON data, you need to create a web method to handle your request. Read this article, it will help you. It shows you how to return simple text, but you can return JSON too. Information on this MSDN article.
Finally, to make sure jQuery is parsing the server response as JSON, change your request and indicate it explicitly:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
dataType: 'json',
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}

MVC4 AJAX post JSON

this is my function, where i post json only
function test() {
var imgFile = document.getElementById('image');
// var imgData = JSON.stringify(getBase64Image(imgElem));
//var imgData = Convert.FormBase64String(imgElem);
$.ajax({
type: 'POST',
dataType: 'json',
url: "http://localhost:59102/Contacts/AddContact",
data: "json=" + "{\"token\":\"8mVm/nS1OfpU+nlQLbJjqXJ7kJI=VyLGI2GEKkGgtDt0babrAw==\"}",
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
},
processData: false,
async: false
});
and i dont know how to add to my data, image, i need to post json and image
this is my controller
[HttpPost]
[AllowAnonymous]
public JsonResult AddContact(string json, HttpPostedFileBase file)
{}
You can't upload files via AJAX (by design) unless you use a plugin that utilises other 'technology' such as flash, or iframes - this is a security measure as JavaScript reading local files on your machine would not be the best idea
There's an option here: http://jquery.malsup.com/form/
...otherwise I suggest looking up one of the many other alternatives!
after you getting the data to a base 64 , your json should be an object
from your controller your json should be something like this
{"json":"something here that is a string","file":"some file"}
Also on the client side you should have a n object on which you invoke JSON.stringify()
var ob = {json:imageDataAsBase64,file:fileDataAsBinary}
although I dont see the reason to send both.
if what you need is just transafering an image that you just need to get the image as base64 and post it as a json

$.Ajax POST, accessing return data

I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.
On my .cs file I have the following Webmethod
[WebMethod]
public static string IsJobEditable(int jobid)
{
try
{
string isEditable = "false";
JobsBLL jbl = new JobsBLL();
int jobStatusId = jbl.GetJobStatusId(jobid);
if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
{
isEditable = "true";
}
return isEditable;
}
catch (Exception ex)
{
throw ex;
}
}
This function in this case will ALWAYS return TRUE as a string.
On Aspx page I have the following
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (result) {
alert(result);
// This is written out in the alert {"d":"true"}
// I want this in a variable as a string
// so I can do a check on it before I do some other actions
// The format is not a String so i cannot split on it to
// retrieve the "true" part.
},
error: function (err, result) { alert(err); }
});
});
As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.
So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).
Use result.d to get your string.
See this site for an explanation of the .d issue when calling .ajax from ASP.NET: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
try alert(result.d);
You can easily retrieve the "true" part like this:
alert(result.d);
The reason the object is wrapped in the "d" json object is security. You can read about it for example here.
According to two articles I found, I think you want to specify "DataType" as json not as text (since you're expecting a content-type of json to be returned). That may be your issue, though i don't have a sample project in front of me to test on. Your result is also probably result.d as outlined in those same articles.
This solved it:
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
//I finally got the data string i wanted
var resultAsString = result.d;
},
error: function (err, result) { alert(err); }
});
});
So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.
What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.
Thanks you to all who contributed to this answer.

Categories