0

作为文件上传 (ASP.NET MVC3) 的一部分,将 id 和 enctype 属性添加到 HTML.BeginForm 将 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 - 谁能告诉我我做错了什么或者有更好的方法吗?

4

3 回答 3

1

在浪费了很多时间之后,我觉得它对你有帮助。就用这个

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

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

于 2015-10-21T11:09:28.263 回答
0

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

 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) {

        });
    });
}
于 2015-08-23T00:21:38.550 回答
0

尝试从 id 和 enctype 中删除 @

于 2015-08-17T03:13:39.247 回答