Why aren't file uploads binding to my viewmodel?

吃可爱长大的小学妹 提交于 2020-01-03 06:01:11

问题


I'm trying to bind file uploads to a ViewModel (as demonstrated in this post).

But I can't get the files to bind to the Files property on the ViewModel.

Please see the code below. What am I doing wrong?

(Edit for clarity - I'd like the uploads to bind to the VM, not have them as an Action parameter.)

ViewModel

public class PrimaryImageUploadViewModel
{
    public PrimaryImageUploadViewModel()
    {
    }

    public HttpPostedFileBase[] Files { get; set; }
    public string Title { get; set; }
}

Action

[HttpPost]
public async Task<ActionResult> Upload(PrimaryImageUploadViewModel postedModel)
{
    var requestFiles = postedModel.Files;  // THIS VALUE IS NULL - WHY?
    foreach (var f in requestFiles)
    {
        if (f.ContentLength == 0)
        {
            // do stuff
        }

    }
}

Request Headers

Accept:*/*
Content-Disposition:attachment; filename="MyImage.png"
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Origin:http://localhost:52588
Referer:http://localhost:52588/example/edit/1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload

------WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Content-Disposition: form-data; name="Title"

Some Test Title
------WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Content-Disposition: form-data; name="files[]"; filename="MyImage.png"
Content-Type: image/png


------WebKitFormBoundaryEj8zSF9hwGU3ZQA9--

回答1:


 public class Model1
    {
        public HttpPostedFileBase[] Files { get; set; }
        public string Title { get; set; }
    }

Hope this helps...




回答2:


First Make sure you've set the enctype attribute on your form to multipart/form-data on your form if you want to be able to upload files:

You can access uploaded file in post action parameter,

[HttpPost]
public async Task<ActionResult> Upload(PrimaryImageUploadViewModel postedModel, HttpPostedFileBase file)
{
    if (file.ContentLength > 0)  
    {  
        string _FileName = Path.GetFileName(file.FileName);  
        string _path = Path.Combine(Server.MapPath("~/UploadedFilesFolder"), _FileName);  
        file.SaveAs(_path);  
    }            
}


来源:https://stackoverflow.com/questions/48767682/why-arent-file-uploads-binding-to-my-viewmodel

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