简体   繁体   中英

MVC4 AJAX post JSON

this is my function, where i post json only

function test() {
            var imgFile = document.getElementById('image');
            //            var imgData = JSON.stringify(getBase64Image(imgElem));
            //var imgData = Convert.FormBase64String(imgElem);

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: "http://localhost:59102/Contacts/AddContact",
                data: "json=" + "{\"token\":\"8mVm/nS1OfpU+nlQLbJjqXJ7kJI=VyLGI2GEKkGgtDt0babrAw==\"}",

                success: function (returnPayload) {
                    console && console.log("request succeeded");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console && console.log("request failed");
                },

                processData: false,
                async: false
            });

and i dont know how to add to my data, image, i need to post json and image

this is my controller

[HttpPost]
        [AllowAnonymous]
        public JsonResult AddContact(string json, HttpPostedFileBase file)
        {}

You can't upload files via AJAX (by design) unless you use a plugin that utilises other 'technology' such as flash, or iframes - this is a security measure as JavaScript reading local files on your machine would not be the best idea

There's an option here: http://jquery.malsup.com/form/

...otherwise I suggest looking up one of the many other alternatives!

after you getting the data to a base 64 , your json should be an object from your controller your json should be something like this

{"json":"something here that is a string","file":"some file"}

Also on the client side you should have an object on which you invoke JSON.stringify()

var ob = {json:imageDataAsBase64,file:fileDataAsBinary}

although I dont see the reason to send both. if what you need is just transafering an image that you just need to get the image as base64 and post it as a json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM