Post modelcontaining HttpPostedFileBase file along with some parameters using form.serialize() in mvc4

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

I have a ViewModel containing some string and HttpPostedFileBase properties . When i am posting the model to the controller using below ajax call,

 $.ajax({                 url: '@Url.Action("_AddFeedback", "Mcq")',                 type: 'post',                  data: $('form#frm-feedback').serialize(),               //  data: formData,                  success: function (data) {                     alert("done");                 },                 error: function (data) {                     alert("Error occured while saving Option's data.");                 }             });

I am getting value for string but null for HttpPostedFileBase type properties. How can we post HttpPostedFileBase file using ajax ??

回答1:

Unfortunately, you cannot send files with AJAX, when serializing the form, but luckily there is another way, if you don't mind using HTML5. A short example, as per this answer:

Markup:

<form id="upload-form" enctype="multipart/form-data">     <input name="file" type="file" />     <input type="button" id="submit" value="Upload" /> </form>

Javascript:

$('#submit').click(function (e) {     e.preventDefault();     var formData = new FormData($('#upload-form')[0]);     $.ajax({         url: '@Url.Action("_AddFeedback", "Mcq")',         type: 'POST',         data: formData,         cache: false,         contentType: false,         processData: false     }); });

As stated, this is an HTML5 approach, which means it won't necessarily work in every browser. If this is a problem, see the thread I've linked to for other approaches to this problem.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!