Solved

Using Ajax to upload JSON to WebApi function

Posted on 2014-09-30
11
288 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
ID: 40353185
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 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 50 total points
ID: 40353231
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
ID: 40354627
@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
Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

 
LVL 82

Expert Comment

by:leakim971
ID: 40354650
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
ID: 40354693
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
 
LVL 26

Author Comment

by:EddieShipman
ID: 40354725
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 75

Expert Comment

by:käµfm³d 👽
ID: 40354853
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
ID: 40354911
don't strinfigy your data :
 data: JSON.stringify(post_data),
just use :
 data: post_data,
0
 
LVL 26

Author Closing Comment

by:EddieShipman
ID: 40354948
@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 75

Expert Comment

by:käµfm³d 👽
ID: 40354971
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
ID: 40356106
@kaufmed, It is going to be passed to the PHP script that will send the data.
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
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…

773 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