Solved

Using Ajax to upload JSON to WebApi function

Posted on 2014-09-30
11
282 Views
Last Modified: 2014-10-01
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.
0
Comment
Question by:EddieShipman
  • 5
  • 3
  • 3
11 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 450 total points
Comment Utility
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
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 50 total points
Comment Utility
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
 
LVL 26

Author Comment

by:EddieShipman
Comment Utility
@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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
your question talk about sending JSON to WebApi
We're now sending binary, you CANNOT send binary file using JSON.
0
 
LVL 26

Author Comment

by:EddieShipman
Comment Utility
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 26

Author Comment

by:EddieShipman
Comment Utility
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
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
don't strinfigy your data :
 data: JSON.stringify(post_data),
just use :
 data: post_data,
0
 
LVL 26

Author Closing Comment

by:EddieShipman
Comment Utility
@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
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
 
LVL 26

Author Comment

by:EddieShipman
Comment Utility
@kaufmed, It is going to be passed to the PHP script that will send the data.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now