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.
You cannot post/upload a file using jQuery Ajax, unless you are going to use FormData
or some plugins which internally use iFrame
implementations.