Using Ajax to upload JSON to WebApi function

I'm rather new to this WebApi stuff and this is my WebApi function:
    [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");
        }
    }

Open in new window

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');
        }
    
    });

Open in new window

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.
LVL 26
Eddie ShipmanAll-around developerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
the problem : You need to create model which match with you JSON data/object
how to fix it : so start by creating a class
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
käµfm³d 👽Commented:
You can do as leakim971 mentions, but you can also get away with simple parameters. You haven't shown the HTML, but I assume you have X number of form fields on your page. You can create a parameter on your Web API method for each form field that you have on the page. You would name your variables the same name as the name property of the form inputs on your page--don't use id; it must be name (as far as posting the form is concerned).

If you go the class route as mentioned by leakim971, then each property of the class should be named the same as the form inputs' name attributes. I usually make the determination of class versus simple parameters based on how many inputs there will be or how complex the data model actually is.

Web API is also smart enough to figure out simply data types as well, so don't think that you are limited to just using string for your types.
0
Eddie ShipmanAll-around developerAuthor Commented:
@leakim971, I need to be able to send files of different types, it may be binary, it may be text, The code above doesn't show that, however. How would I write the class to be able to accept different file types?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

leakim971PluritechnicianCommented:
your question talk about sending JSON to WebApi
We're now sending binary, you CANNOT send binary file using JSON.
0
Eddie ShipmanAll-around developerAuthor Commented:
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.
0
Eddie ShipmanAll-around developerAuthor Commented:
So I modified to this but my upload class is empty, null strings and PID = 0.

    [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");
        }
    }

Open in new window


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; }
    }

Open in new window


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>

Open in new window

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');
                }
    
            });
        });
    });//]]>

Open in new window

0
käµfm³d 👽Commented:
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">

Open in new window

0
leakim971PluritechnicianCommented:
don't strinfigy your data :
 data: JSON.stringify(post_data),
just use :
 data: post_data,
0
Eddie ShipmanAll-around developerAuthor Commented:
@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...
0
käµfm³d 👽Commented:
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   = )
0
Eddie ShipmanAll-around developerAuthor Commented:
@kaufmed, It is going to be passed to the PHP script that will send the data.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.