Eddie Shipman
asked on
Using Ajax to upload JSON to WebApi function
I'm rather new to this WebApi stuff and this is my WebApi function:
Note: I'm only using ajax in my test, I will be converting to PHP cURL when I get the WebAPi functionality working.
[HttpPost]
[Route("api/UploadToArchive")]
public IHttpActionResult UploadToArchive([FromBody]string JSON)
{
Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(JSON);
int PID = (int)jObject["PID"];
string LT = (string)jObject["LT"];
string HTML = System.Web.HttpUtility.HtmlDecode((string)jObject["HTML"]);
string Title = System.Web.HttpUtility.HtmlDecode((string)jObject["Title"]);
string lt2 = getLT(PID.ToString());
if (lt2 == LT)
{
// Upload the file to the archive using the UpdateArchive() function:
_Repository.UpdateArchive(HTML, Title, "", PID);
return Ok(PID);
}
else
{
return BadRequest("Invalid LT");
}
}
I've got the following Ajax code to send json data to my WebAPI. I have encoded HTML string in one of the fields being posted. All my fields are converted to JSON before sending. $.ajax({
async: true,
cache: false,
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: upload_url,
data: JSON.stringify(post_data),
dataType: 'json',
beforeSend: function () {
console.log('Fired prior to the request');
},
success: function (data) {
console.log('Fired when the request is successfull');
$('.document').append('<p>' + 'UploadTest:' + JSON.stringify(data) + '</p>');
},
error: function(jqxhr, errorText, errorThrown) {
console.log('Error Thrown');
$('.document').append('<p>' + 'UploadTest:' + upload_url + "</br>" + $(this).data + '</p>');
},
complete: function () {
console.log('Fired when the request is complete');
}
});
I put a break point on the first line of my WebAPI function and JSON is null. What is the problem and how do I fix it? Note: I'm only using ajax in my test, I will be converting to PHP cURL when I get the WebAPi functionality working.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
your question talk about sending JSON to WebApi
We're now sending binary, you CANNOT send binary file using JSON.
We're now sending binary, you CANNOT send binary file using JSON.
ASKER
Forget what I said. I changed my mind. I will be sending just form fields and have created the class. Am looking into how it is being sent, now.
ASKER
So I modified to this but my upload class is empty, null strings and PID = 0.
ArchiveUpload class:
HTML form:
[HttpPost]
[Route("api/UploadToArchive")]
public IHttpActionResult UploadToArchive(ArchiveUpload upload)
{
string HTML = upload.HTML;
string Title = upload.Title;
string LT = upload.LT;
int ParticipantID = upload.PID;
string lt2 = getLT(PID.ToString());
if (lt2 == LT)
{
// Upload the file to the archive using the UpdateArchive() function:
_Repository.UpdateArchive(HTML, Title, "", PID);
return Ok(PID);
}
else
{
return BadRequest("Invalid LT");
}
}
ArchiveUpload class:
public class ArchiveUpload
{
public string LT { get; set; }
public int PID { get; set; }
public string Title { get; set; }
public string HTML { get; set; }
}
HTML form:
<body>
<div class="document">
<a class="upload" id="ul" href="#">Upload to Archive test</a><br />
<textarea id="html">
<span>usually have some long HTML posted here</span>
</textarea>
</div>
</body>
javascript to post: var vLT = 'c40210542a253a8357e1c0b0e3eb82235fd1a68626';
$(function () {
$('.document').on('click', '.upload', function (e) {
e.preventDefault();
var post_data = {PID: 1158341,
Title: "CFL Confirmation",
LT: vLT,
HTML: $("#html").val()
};
var upload_url = 'http://localhost:49494/api/UploadToArchive/';
$.ajax({
async: true,
cache: false,
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: upload_url,
data: JSON.stringify(post_data),
dataType: 'json',
beforeSend: function () {
console.log('Fired prior to the request');
},
success: function (data) {
console.log('Fired when the request is successfull');
$('.document').append('<p>' + 'UploadTest:' + JSON.stringify(data) + '</p>');
},
error: function(jqxhr, errorText, errorThrown) {
console.log('Error Thrown');
$('.document').append('<p>' + 'UploadTest:' + upload_url + "</br>" + jqxhr.responsetext + '</p>');
},
complete: function () {
console.log('Fired when the request is complete');
}
});
});
});//]]>
Controls you post to the server need to have a name property whose value matches the model's corresponding property name. id is only useful for getting to a control via Javascript. In other words, your <textarea> needs to be:
<textarea id="html" name="html">
don't strinfigy your data :
data: JSON.stringify(post_data),
just use :
data: post_data,
data: JSON.stringify(post_data),
just use :
data: post_data,
ASKER
@kaufmed, name is not needed when doing it like this. Adding the class and removing the JSON.stringify was the solution. I now have it working.
Thanks to both of you. Now to convert the ajax to PHP cURL...
Thanks to both of you. Now to convert the ajax to PHP cURL...
I did not realize you were hard-coding the data into the AJAX call. I just assumed it was coming from the form. Whatever works, I guess = )
ASKER
@kaufmed, It is going to be passed to the PHP script that will send the data.
ASKER