2

I am trying to send array of json data and image file with ajax but i can only get image file and not getting json data and i can see json data sent properly in fiddler though.In action method, collection parameter for json data says count=0. How can i get array of json data?

@using (Ajax.BeginForm("GetData", "Home", new AjaxOptions
{
    InsertionMode = InsertionMode.Replace
}, new { @id = "form_", enctype = "multipart/form-data" }))
{
    @Html.TextBox("imagefile", null, new { @type="file"})
    @Html.Hidden("formdata", null, new { @data_formdatajson = "" }))
    @Html.TextBox("submit", null, new { @id = "button", @value = "upload", @type = "submit"})
}

    var DataClass = {
            data1: data1value,
            data2: data2value
        }

dataArray=[];
dataArray.push(DataClass);
dataArrayJson = JSON.stringify(dataArray);
$('#formdata’).data("formdatajson ", dataArrayJson);

           $('#form_').on('submit', function (e) {
                var dataArray_ = $('#formdata ').data("formdatajson");
                var formdata = new FormData($(this)[0]);
                formdata.append('formdata', dataArray_);
                        $.ajax({
                            url: '/GetData/Home/',
                            type: 'POST',
                            data: formdata,
                            processData: false,
                            contentType: false,
                            dataType: "json",
                            success: function (data) {
                            },
                            error: function () { },
                        });
                    });
public class DataClass
{
     public string data1 { get; set; }
        public string data2 { get; set; }
}

        [HttpPost]
        public JsonResult GetData(IEnumerable<DataClass> formdata, HttpPostedFileBase imagefile)
        {
                    return Json(new { success = true },  JsonRequestBehavior.AllowGet);
        }
4
  • You should use formdata.append('formdata', dataArray_); instead of formdata.append('dataarray', dataArray_); Commented Jan 20, 2016 at 11:33
  • nope this didnt help:( Commented Jan 20, 2016 at 11:48
  • Have you tried setting contentType to "application/json" instead of to false? Commented Jan 20, 2016 at 15:46
  • @stephen.vakil yes i tried...i got error 500. Commented Jan 20, 2016 at 20:26

1 Answer 1

0

i fixed the problem...I dont know why but Asp.Mvc gets json data and add an empty element to outside of json array for no reason.I used request.form to get json and i eliminated this additional data by using substring.Now it works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.