i have submit code,
$('#form').on('submit',function (e) { e.preventdefault(); //var file = $("#productimg"); var fileupload = $("#productimg").get(0); var files = fileupload.files; var form = $("#form"); var formdata = new formdata(); formdata.append("product", form.serialize()); // looping on files , add formdata object (var = 0; < files.length; i++) { formdata.append(files[i].name, files[i]); } //formdata.append("file", file); $.ajax({ type: 'post', url: baseurl + 'controller/action', data: formdata, processdata: false, contenttype: false, success: function (data) { } }); });
this controller :
public jsonresult addproduct(productmodel product) // data binded in model if remove content type property { var issuccess = false; if (product != null) { try { if (request.files.count > 0) // works ok if added content type property { var sadas = "sad"; }
so what's happening here sending serialized form
data mvc controller uploaded file.
the problem here , when added ajax property contenttype: false,
, can postback files, binded model null.
on other hand, if remove property, binded model works ok. problem file not sent in server.
how can make work? want both form , images sent in server side.
update working now, line changed this
formdata.append("product", form.serialize());
to
var other_data = $('#addproductform').serializearray(); $.each(other_data, function (key, input) { formdata.append(input.name, input.value); });
can explain happening? got no clue
unfortunately jquery serialize()
method not include input file elements. files not going included in serialized value.
what can is, creating formdata
object, append files that. need append form field values same formdata object. may loop through input field , add it.
when add files form data, need give name match parameter use in httppost action method.
this should work.
var fileupload = $("#productimg").get(0); var files = fileupload.files; var formdata = new formdata(); // looping on files , add formdata object (var = 0; < files.length; i++) { console.log('(files[i].name:' + files[i].name); formdata.append('productimg', files[i]); } // can update jquery selector use css class if want $("input[type='text'").each(function (x, y) { formdata.append($(y).attr("name"), $(y).val()); }); $.ajax({ type: 'post', url: 'replacehereyoururltotheactionmethod', data: formdata, processdata: false, contenttype: false, success: function (data) { } });
and action method, can add parameter of type ienumerable<httppostedfilebase>
name same set form data, productimg
.
[httppost] public virtual actionresult index(productmodel model, ienumerable<httppostedfilebase> productimg) { // :look through productimg , }
Comments
Post a Comment