简体   繁体   中英

Sending HttpPostedFileBase field using JQuery ajax form.serialize() in MVC

I'm working on an MVC project.I have a form Like below:

<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>

My ViewModel:

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

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

}

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

My Controller Action is like this:

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

    }

Before this situation I faced,I mean in other projects,mostly I had about 3 to 8 field's including image file an some other types and I append them one by one to FormData (because of that Image file) then send them through ajax request and it was no matter for me,but now I have about 22 field's and it's a little though to do this.so I decided to serialize the form and send it through ajax request and it's working good form all filed's except Image which I make it the type HttpPostedFileBase in ViewModel. Any Idea how to send this field with form using data: form.serialize() ?

appreciate your help :)

Update: let me clear some point's:

1-I don't want FormData to send through ajax and I want to send using form.serialize() .

2-Don't want to use ready file plugins.

3-I don't mean just one image field ,I mean whole the form with 23 field's.

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

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