File data null in File uploading using REST - c#

And i have the following code
self.upload = function (file) {
var path = $('#fileUpload').val();
var fr= new FileReader();
var ID = JSON.stringify({
ID:23,
Name: file.name,
Type: file.type,
Size: file.size,
Path: path,
data:fr.readAsDataURL(file),
});
$.ajax({
cache: false,
url: "http://localhost:49589/api/files",
type: "POST",
dataType: "json",
data: ID,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
},
error: function (json) {
alert("error" + JSON.stringify(json));
}
});
im performing file upload . and my controller is
[HttpPost]
public string upload(filesUpload f)
{
byte[] jj = f.data; // **getting null here**
string givenId = f.Path;
return givenId;
}
when i execute this and upload a file im getting null file data . where filesUpload is my model
what went wrong in my code . Im using Knockout.js for viwe and drundal SPA framework
is there any other way to do . kindly help me

FileReader.readAsDataURL reads the file asyncronically and return nothing. You should at first start read the file, then catch fr.onload event and from here create your json object and call ajax.
upd: The code will look like this:
self.upload = function (file) {
var path = $('#fileUpload').val();
var fr= new FileReader();
fr.onload = function (frEvent) {
var ID = JSON.stringify({
ID:23,
Name: file.name,
Type: file.type,
Size: file.size,
Path: path,
data:frEvent.target.result,
});
$.ajax({
cache: false,
url: "http://localhost:49589/api/files",
type: "POST",
dataType: "json",
data: ID,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
},
error: function (json) {
alert("error" + JSON.stringify(json));
}
});
};
fr.readAsDataURL(file);
};

Related

Ajax error calling web method

I am trying to set the date in a Bootstrap datetime picker based on drop down list selection change. I am using a web method (C#) to return "start date" given a "certificate ID".
I tried using "text" data type instead of "json" but keep getting "Cannot convert object of type System.String to type System.Collections.Generic.IDictionary"
I searched for this error type and could not find something that would resolve this issue.
$("#ddlCertificate").change(function () {
....
debugger
setStartDate($("#ddlCertificate").val());
});
function setStartDate(certItemID) {
var param = JSON.stringify(certItemID, null, 2);
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: param,
}).done(function (result) {debugger
$("#tbStartDate").val(result.d);
}).fail(function (jqXHR, textStatus, errorThrown) {debugger
alert(textStatus + ' - ' + errorThrown);
});
}
Web Method:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string GetCertItemStartDate(string certID)
{
int iCertItemID = int.Parse(certID);
DateTime dtStartDate = CertItem.GetCertItemStartDate(iCertItemID);
string JSONresult;
JSONresult = JsonConvert.SerializeObject(dtStartDate);
return JSONresult;
}
The problem was the way the parameter was being passed. In ajax call, I had:
data: param,
and had to change it to:
$("#ddlCertificate").change(function () {
....
var certID = "{ 'certID': '" + $('#ddlCertificate').val() + "'}";
setStartDate(certID);
});
function setStartDate(certItemID) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: certItemID,
}).done(function (result) {
var startDate = JSON.parse(result.d);
setStartDate(new Date(startDate));
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown);
});
}

ajax posting formdata error status 200 OK

I am trying to upload file using Ajax.
The Error status is 200 ok .
Response text is my MasterPage HTML Code.
The Request never went to the Back-end as i am debugging with a breakpoint into the method.
so far i have tried this.
C# WebMethod
[HttpPost]
public void Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
file.SaveAs(path);
}
}`
Ajax Request
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
in ajax call you have to delete dataType: json because files must be sent multipart/form-data
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
Please try this code
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
return reader.result;
};
reader.onerror = function (error) {
return '';
};
}
function uploadFiles() {
var files=[];
$.each(files, function (key, value) {
var x=getBase64(value)
if(!!x)
files.push(x);
});
$.ajax({
type: 'POST',
url: '/Home.aspx/Upload',
data: JSON.stringity({files:files}),
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
[System.Web.Services.WebMethod]
public static void Upload(string[] files)
{
//Convert base64 to file format and save
}

angularjs and webmethod return json

When I use jquery $ajax, I get the data as json
But when using angular http service, I get the response as xml.
This is my both code (angular and jquery ajax)
var _getList = function () {
var list = [];
var deferred = $q.defer();
$.ajax({
type: "POST",
url: '/Landing/manage/WebService.asmx/GetList',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data && data.d) {
list = data.d;
deferred.resolve(list);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
deferred.reject(xmlHttpRequest);
}
});
//angular
$http({
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: '/Landing/manage/WebService.asmx/GetList',
headers: {
"Content-Type": "application/json"
}
}).success(function (data) {
console.log(data);
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
And this is my web method code With json format return
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat =
System.Web.Script.Services.ResponseFormat.Json)]
public tblCampaignCollection GetList()
{
tblCampaignCollection coll = Campaign.AdminGetAll();
return coll;
}
The request you are performing is not a real POST Request, I had a similar issue, if you read the console network TAB you will see that it is a GET request.
What I do if I want to perform a POST in a service is the following:
function myService(xxxParam) {
var request = $http({
method: 'POST',
headers: {"Content-Type": 'text/plain; charset=UTF-8'},
url: serviceURL,
data: {
firstPostParam: "string",
secondPostParam: 1,
thirdPostParam: xxxParam
}
});
return ( request.then(handleSuccess, handleError) );
}
try with
$http({
method: 'POST',
url: '/Landing/manage/WebService.asmx/GetList',
headers: {
"Content-Type": 'application/json; charset=UTF-8'
},
data: {
dataType: "json"
}
})...
I hope it helps.

Call WebMethod using jQuery

Hi i want to pass the values from jQuery and assign those values to a class model which is used in a method.
Following is my script:
$(document).ready(function(){
$('#BtnSubmit').click(function () {
var CollegeName = $('#TxtCollegeName').val();
var CollegeAddress = $('#TxtCollegeAddress').val();
var pageUrl = '<%=ResolveUrl("~/AddNewCollege.aspx/CreateCollegeData")%>';
$.ajax({
type: 'Post',
url: pageUrl,
data: JSON.stringify({ "CollegeName": CollegeName, "CollegeAddress": CollegeAddress}),
dataType: 'text',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
},
error: function () {
alert("An error occurred.");
}
});
});
});
Below is my Csharp method:
[WebMethod]
public static string CreateCollegeData(CollegeDetails collegeDetails)
{
CollegeDAL obj = new CollegeDAL();
bool b = obj.InsertCollegeDetails(collegeDetails);
return "success";
}
But debugger is unable to call the web method. Every time the following message is coming:
Try declaring your object ahead of time: link
I got another solution.
$('#BtnSubmit').click(function () {
var collegeDetails = {};
collegeDetails.CollegeName = $('#TxtCollegeName').val();
collegeDetails.CollegeAddress = $('#TxtCollegeAddress').val();
$.ajax({
type: 'POST',
url: 'AddNewCollege.aspx/CreateCollegeData',
data: "{collegeDetails:" + JSON.stringify(collegeDetails) + "}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
$('#TxtCollegeName').val('');
$('#TxtCollegeAddress').val('');
},
error: function () {
alert("An error occurred.");
}
});
});

returning complete page HTML instead of string output in JSON response

I am trying to achieve a simplest task through ajax using web method . My web method as follow
[WebMethod]
public static string GetDate()
{
return string.Format("says {0}", DateTime.Now.ToString("r"));
}
and ajax code as follow
$(document).ready(function() {
$("#Result").click(function() {
alert('Result Clicked');
$.ajax(
{
type: "POST",
url: "test1.aspx/GetDate",
data : "{}",
contentType: "application/json",
dataType: "json text",
success: function(rsp) {
alert('success');
alert(rsp);
alert(rsp.d);
$('#Result').append(rsp.d);
},
error: function(rsp) {
alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
console.log(rsp);
console.log(rsp.responseText);
}
});
});
});
but status says OK and 200 status code, but instead of simple string in rsp.d its shows complete HTML of that page self.
You Can Try this Code May be it is Help Full.
$("#Result").click(function () {
alert('Result Clicked');
$.ajax(
{
type: "POST",
url: "Default.aspx/GetDate",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (rsp) {
alert('success');
alert(rsp);
alert(rsp.d);
$('#Result').append(rsp.d);
},
error: function (rsp) {
alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
}
});
});

Categories