多个属性 Html.BeginForm MVC id 和 enctype 作为文件上传的一部分

Multiple Attributes Html.BeginForm MVC id and enctype as part of file upload

作为文件上传的一部分(ASP.NET MVC3)将 id 和 enctype 属性添加到 HTML.BeginForm return HttpPostedFileBase 为 null

型号:

public class ProfileModel
{
 [UIHint("Upload")]
 public HttpPostedFileBase ImageUpload { get; set; }
}`

ProfileForm.cshtml

@using (Html.BeginForm("Update", "Profile", new { ProfileId = ViewBag.ProfileID }, FormMethod.Post, new { @enctype = "multipart/form-data", @id = "ProfileForm" }))
{

    <div>
        @Html.LabelFor(model => Model.ImageUpload)
        @Html.TextBoxFor(model => Model.ImageUpload, new { type = "file" })
    </div>
    <div class='buttons'>
        <input type="submit"  value='Save' />
    </div>
}

控制器

public Upload(ProfileModel viewModel)
{
  if (viewModel.ImageUpload != null && viewModel.ImageUpload.ContentLength > 0)
 {
   var uploadDir = "~/uploads";
   var imagePath = Path.Combine(Server.MapPath(uploadDir), viewModel.ImageUpload.FileName);
   var imageUrl = Path.Combine(uploadDir, viewModel.ImageUpload.FileName);
   viewModel.ImageUpload.SaveAs(imagePath);
   }
}

如果我如下所示删除 @id = "ProfileForm" 属性,我将获得 HttpPostedFileBase (ImageUpload) 值。

@using (Html.BeginForm("Update", "Profile", new { ProfileId = ViewBag.ProfileID }, FormMethod.Post, new { @enctype = "multipart/form-data"}))
{  }

我需要同时传递 id 和 enctype - 谁能告诉我我做错了什么或者有更好的方法吗?

尝试从 id 和 enctype 中删除@

我已经通过以下操作解决了这个问题: - 单击提交后,我首先通过调用以下方法单独放置图像

 function FileUploadClick() {

            var formData = new FormData();
            var totalFiles = document.getElementById("FileUpload").files.length;
            for (var i = 0; i < totalFiles; i++) {
                var file = document.getElementById("FileUpload").files[i];

                formData.append("FileUpload", file);
            }

            $.ajax({
                type: "POST",
                url: '/Profile/Upload',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    alert('succes!!');
                },
                error: function (error) {
                    alert("errror");
                }
            });
        }

function Submit() {

    $("#ProfileForm").submit(function (e) {
        FileUploadClick();
        var url = "/Profile/Update";
        $.post(url, $("#ProfileForm").serialize(), function (data) {

        });
    });
}

在浪费了很多时间之后,我认为 you.Just 使用这个

很有帮助
@using (Html.BeginForm("Update", "Profile", new { @id = "ProfileForm" }, FormMethod.Post, new { @enctype = "multipart/form-data",  }))

你的 id 会在那里 new { @id = "ProfileForm" }