繁体   English   中英

使用Ajax将对象发送到ASP.NET MVC中的控制器

[英]Sending object to a controller in asp.net mvc using ajax

我在将对象包含数组发送到控制器时遇到问题

这是我的js代码

  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();
        }
    });

这是我的控制方

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

我的问题是ajax请求始终将to数组发送为null,我不知道出了什么问题,因此有人可以帮助我解决此问题。

你能改变你的要求和使用

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

这应该工作。 请告诉我。

尝试这个。 将对象推送到数组并将其作为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);
        }
    });

将控制器函数的返回类型转换为JSonResult。 希望会有所帮助。

您要使用ajax上传文件吗?

使用表单的正常用法而不是Ajax.BeginForm,然后在表单提交事件中编写如下代码:

 $('#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;
         })

控制器中的服务器端:

    [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);
    }

    }

您可以尝试其他方法。 您可以通过执行以下操作来序列化整个表单:

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

然后将其发布到控制器:

   $.ajax(
            {
                type: "POST",
                data: formdata,
                dataType: 'json',...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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