0

I have issue with sending object contains array to a controller

this is my js code

  var messageId = 0;
    function DraftMessage()
    {
        var to = [];
        var i = 0;
        $('#to option:selected').each(function (index, element) {
            to[i++] = $(element).val();
        });
        console.log(to);
        $.ajax({
            type: "POST",
            url: "@Url.Action("DraftMessage", "Activities")",
            datatype: "json",
            traditional: true,
            async: false,
            data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
                beforeSend: function () { }
        }).done(function (Id) {
            console.log(Id);
            messageId = Id;
        });
    }
    $("input, select, textarea").change(function () { DraftMessage(); });
    var contents = $('.note-editable').html();
    $(".compose-message").on("blur", ".note-editable", function () {
        if (contents != $(this).html()) {
            DraftMessage();
            contents = $(this).html();
        }
    });

and this is my controller side

    public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
    {
        return new MessageActions().DraftMessage(draftMessage);
    }

my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.

Haidar
  • 123
  • 1
  • 12
  • 1
    where are you adding the file input data array to the data ? Take a look at this http://stackoverflow.com/questions/34603739/jquery-ajax-form-submit-that-contains-files/34604232#34604232 – Shyju May 07 '16 at 19:25

4 Answers4

0

Can you change your request and use

dataType: "json",
contentType: "application/json;charset=utf-8",

This should work. Please let me know.

Lalit Kale
  • 557
  • 6
  • 13
0

Try this. Push your object to array and send it as Json.

array.push({yourobject datas here})
    $.ajax({
        type: "POST",
        url: '/DraftMessage/Activities',
        contentType: 'application/json',
        data: JSON.stringify(array),
        success: function (d) {
            ..
        },
        error: function (xhr, textStatus, errorThrown) {

            console.log(errorThrown);
        }
    });

Convert your controller function's return type to JSonResult. Hope helps.

Berkay Yaylacı
  • 4,383
  • 2
  • 20
  • 37
0

do you want upload file using ajax ?!!

use the normal usage of form not the Ajax.BeginForm then in form submit event write your code like this:

 $('#Form').submit(function () {
        var xhr = new XMLHttpRequest();
        var fd = new FormData();

        var file = $('#Image').val();
        if (file) {
            var fname = $('#Image')[0].files[0].name;

            if (CheckFile(file)) {
                var uploadFile = document.getElementById('Image').files[0];
                var myArray = [];
                myArray.push(uploadFile);
                if (myArray.length > 0) {
                    for (var i = 0; i < myArray.length; i = i + 1) {
                        fd.append("File1", myArray[i]);
                    }
                }
            }
            else {
                return false;
            }
        } 


        fd.append("ID", messageId);
        fd.append("Title", $('#Title').val());
        fd.append("Project", $('#Project').val());
        fd.append("AreaId", $('#AreaId').val());
        fd.append("Body", $('#messageBody').val());

        var form = $('#Form');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        fd.append("__RequestVerificationToken", token);
        xhr.open("POST", "/ControllerName/Action/", true);
        xhr.send(fd);

        xhr.addEventListener("load", function (event) {
        if (event.target.response != "OK") {
            OnFail(event.target.response);
        }
        else {
            OnSuccess(event);
        }
         }, false);
        return false;
         })

server side in controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult actionName(Model pModel){

    HttpPostedFileBase File = Request.Files["File1"];
    if (File != null && File.ContentLength != 0){
                 //do what you want
      return Content("OK");
    }
    else{
     Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return Content("Error Messages",        System.Net.Mime.MediaTypeNames.Text.Plain);
    }

    }
Ali Panahian
  • 305
  • 1
  • 6
0

You can try a different approach. You can serialize your entire form by doing something like this:

var formdata = $("#frmEmailInfo").serialize();

and then post it to the Controller:

   $.ajax(
            {
                type: "POST",
                data: formdata,
                dataType: 'json',...
Sonya
  • 76
  • 1
  • 8