In a Shared (VB) webmethod the Request.Files is not accessible - ajax

from javascript an ajax call to the server is done.
javascript:
function SaveNote() {
var note = quill.root.innerHTML;
var postData = { mediaNote: note };
console.log("SaveNote is called");
$.ajax({
type: "POST",
data: JSON.stringify(postData),
url: "EditTextReport.aspx/SaveNote",
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
success: function (data) {
console.log("SaveNote returned from server with success");
return;
},
error: function (error) {
console.log(error);
}
});
}
Visual Basic code:
Public Shared Sub SaveNote(mediaNote As String)
_noteContent = mediaNote
_IsNoteReceived = True
_staticMe.Save(False)
End Sub
Public Sub Save(sendEmailAfterSave As Boolean)
...
Dim flImages As HttpFileCollection = Request.Files
...
End Sub
On the serverside the request object is needed but this throws an exception:
System.Web.HttpException: 'Request is not available in this context'
I'm looking to find a way of getting the Request object send with the ajax call to the server as a parameter, so it can be used in a shared(static) context.

Related

AJAX dont call WebMethod but returns HTML

I had read a lot of questions here on Stackoverflow about AJAX calls to WebMethods, and I tried a lot of things and nothing works.
My AJAX method doesnt call the WebMethod on server side but returns success and the entire HTML of the page.
This is the AJAX:
$("[id*=butLogin]").click(function () {
var obj = {};
obj.pEmail = "EMAIL"; //$.trim($("[id*=txtName]").val());
obj.pPassword = "PASSWORD"; //$.trim($("[id*=txtAge]").val());
$.ajax({
type: "POST",
url: "login.aspx/logOn",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
failure: function (msg) {
alert(msg.d);
},
error: function (msg, merr, derr) {
alert(msg.d);
}
});
return false;
});
And this is the WebMethod:
[System.Web.Services.WebMethod]
public static string logOn(string pEmail, string pPassword)
{
return "logged";
}
I believe is a simples mistake.
Thanks for your help.

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

json returns undefined when accessing in ajax

I have a controller that return json object I checked the controller and it's working good.
Here is the Sample Result of my controller
{"CompliantCount":0,"NonCompliantCount":0,"StatusOfRiskItems":[{"Id":4,"Status":"Closed","Count":0},{"Id":1,"Status":"Open","Count":0},{"Id":2,"Status":"Mitigating Control Implemented","Count":0},{"Id":3,"Status":"Risk Accepted","Count":0}],"RiskLevelBreakdownOfOpenItems":[{"Id":0,"RiskLevel":"N/A","Count":0},{"Id":1,"RiskLevel":"Low","Count":0},{"Id":2,"RiskLevel":"Medium","Count":0},{"Id":3,"RiskLevel":"High","Count":0},{"Id":4,"RiskLevel":"Very High","Count":0}],"RiskLevelStatusPerDepartment":[],"CompliancePerDepartment":[],"CurrentRiskLevel":"N/A","ComplianceRating":NaN}
But when I consume the json in ajax it return null
function RiskRegisterReport(siteId, programId, departmentId, status, auditType, auditor, auditDate) {
var _data;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8;",
url: hostpath + "/RiskRegister/RiskRegisterReport/",
dataType: "json",
async: false,
data: {
siteId: siteId,
programId: programId,
departmentId: departmentId,
statusId: status,
auditType: auditType,
auditor: auditor,
auditDate: auditDate
},
success: function (data) {
/// after getting the data
/// push the data.Compliant and data.NonCompiant to the array
_data = data;
}
});
return _data;
}

ajax call sharepoint hosted wcf service bad request

I have a WCF service hosted in Sharepoint 2010 (therefore no config file necessary --> ServiceHost Factory set to MultipleBaseAddressWebServiceHostFactory).
My service interface:
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
List<Course> GetAllCoursesByPerno(string empPerno);
My ajax call:
var input = $j("#perno").val();
$j.ajax({
type: "POST",
url: "/_vti_bin/Project/Service.svc/GetAllCoursesByPerno",
dataType: "json",
//data: input,
data: '{"empPerno": "' + input + '"}',
contentType: "application/json; charset=utf-8",
processData: true,
success: function (data) {
var courseData = data;
},
error: function (e) {
alert(e.statusText);
}
});
My method:
public List<Course> GetAllCoursesByPerno(string empPerno)
{
.
.
.
.
}
I get a 400 Bad Request each time. I've tried every which way to compose the data;
data: '{"empPerno": "' + input + '"}',
data: JSON.stringify({ empPerno : input }),
But no cigar. Any help would be appreciated!
Thanks
Use Microsoft ajax library for calling.
This also avoid DateTime deserializing issues
Sys.Net.WebServiceProxy.invoke('/_vti_bin/YourSubfolder/SearchService.svc',
'EmptyMethod',
false,
{data: 'client data'},
function () {
console.log('Success', arguments);
},
function () {
console.log('Eroor', arguments);
}, this);

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