We all know that in order for the form to be able to submit files, we need to specify the attribute enctype=multipart/form-data on the form so that files can be uploaded. There are many articles about enctype, so I won’t explain it here.
The problem is that MVC's Html.BeginForm() is used to output the form code. Enctype is not added by default.
@using (Html.BeginForm()) {
}
There is a < in PartialView ;input type="file" /> is used to upload files, but I don’t want to modify the Html.BeginForm() of the parent page for this PartialView. My approach is to use a script in PartialView to add enctype to the form:
$(function(){
$('# file').parents('form').attr('enctype', 'multipart/form-data');
});
Have the recent mainstream browsers passed the test? Problem, only a few old versions of IE have problems. I tried manually adding enctype to Html.BeginForm() to solve the problem, which means that the problem lies in the above script. After multiple searches, I finally found that the problem occurs because IE6, 7, and 8 do not support direct attr('enctype', 'multipart/form-data'), but set the dom attribute encoding='multipart/form-data', and the final script code Modify to:
$(function () {
$('#file').parents('form').attr('enctype', 'multipart/form-data').get(0).encoding = 'multipart/form-data';
});