【问题标题】:Sending HttpPostedFileBase field using JQuery ajax form.serialize() in MVC在 MVC 中使用 JQuery ajax form.serialize() 发送 HttpPostedFileBase 字段
【发布时间】:2016-03-30 19:24:22
【问题描述】:

我正在做一个 MVC 项目。我有一个如下所示的表单:

<div id="horizontal-form">
            @using (Html.BeginForm("Send", "Ticket", FormMethod.Post, new
            {
                @class = "form-horizontal",
                role = "form",
                id = "form_send_ticket",
                enctype = "multipart/form-data"
            }))
            {

                @**** I have about 20 filed's of other types here ****@
                 ......

                @**** Image file ****@
                @Html.TextBoxFor(x => x.Image, new { type = "file" })


                <div>
                    <button type="button" class="btn btn-success" id="send_ticket">Insert</button>
                </div>
            }

 </div>

我的视图模型:

  public class SendViewModel
{
    //I have about 20 filed's of other types here
    .....

    //Image file
    public HttpPostedFileBase Image { get; set; }

}

我的 JQuery ajax:

   $("#send_ticket").click(function () {
        var form = $("#form_send_ticket");

        $.ajax({
            type: "POST",
            url: '@Url.Action("Send", "Ticket")',
            data: form.serialize(),
            contentType: "multipart/form-data",
            success: function (data) {
                //do something
            },
            error: function (e) {
               //do something
            }
        });
    })

我的控制器动作是这样的:

 [HttpPost]
    public ActionResult Send(SendViewModel ticket)
    {
       //Do something
       return Json(new { });

    }

在我遇到这种情况之前,我的意思是在其他项目中,大多数情况下我有大约 3 到 8 个字段,包括图像文件和其他一些类型,我将它们一一附加到 FormData(因为那个图像文件)然后发送他们通过 ajax 请求,这对我来说没关系,但现在我有大约 22 个字段,但这样做有点困难。所以我决定序列化表单并通过 ajax 请求发送它,它的工作良好,除了 Image我在 ViewModel 中将其设为 HttpPostedFileBase 类型。知道如何使用data: form.serialize() 发送此字段和表单吗?

感谢您的帮助:)

更新: 让我澄清一点:

1-我不希望 FormData 通过 ajax 发送,我想使用 form.serialize() 发送。

2-不想使用现成的文件插件。

3-我不是说只有一个图像字段,我是指整个表单,有 23 个字段。

【问题讨论】:

  • 请阅读整个问题。就像您提供的一样,他们使用 FormData 通过 ajax 发送,我想使用 form.serialize() 发送,他们建议了一些现成的插件文件并且确实想要,他们只指向一个图像字段并表示整个表单。
  • 参考this answer - 它只是var formdata = new FormData($('form').get(0)); 来序列化您的整个表单,包括文件输入 - 您不需要一个一个地附加它们。

标签: c# jquery ajax asp.net-mvc httppostedfilebase


【解决方案1】:

不能使用 jQuery Ajax 发布/上传文件,除非您打算使用 FormData 或一些内部使用 iFrame 实现的插件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2023-03-26
    • 1970-01-01
    • 2010-10-11
    • 2020-01-14
    • 2013-03-24
    • 1970-01-01
    相关资源
    最近更新 更多