0

FunwarsVM.cs

public class FunwarsVM : IFunwars
{
    public int Id { get; set; }
    public string Date { get; set; }
    public string OurTeam { get; set; }
    public string Status { get; set; }
    public string Opponent { get; set; }
    public string Score { get; set; }
    public int FileID { get; set; }

    public List<Funwars> Funwars { get; set; }

    [NotMapped]
    public  ImageUpload Files { get; set; }

    public FunwarsVM()  
    {
        this.Funwars = new List<Funwars>();
        this.Files = new ImageUpload();
    }
}

ImageUpload.cs

public class ImageUpload
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string MimeType { get; set; }
    public string FilePath { get; set; }


    [NotMapped]
    public List<IFormFile> Images { get; set; }
}

View (only image upload part)

<form id="holder" method="post" action="/Funwars/Add" enctype="multipart/form-data">

    <div class="form-group">

        <h3>Screenshots</h3>

        <input type="file" name="files.images" value="@Model.Files.Images" multiple />

    </div>       
    <input type="submit" name="submit" value="Submit" />
</form>

Controller

[HttpPost]
public async Task<IActionResult> Add(FunwarsVM model)
{

    model.Add();
    return RedirectToAction("Index",model);
}

So guys, I want to pass Image files from view to controller. When I am passing @Model.Files.Images in my view, it means I am passing List<IFormFile> to my model, but it passes null!

but when I add

public List<IFormFile> Images { get; set;}

directly to my FunwarsVM, and then pass @Model.Images to my View, it returns right pictures I am adding!

why won't it work when I am calling that List<IFormFile> object from my View by after I create instance of ImageUpload model, but when i am calling directly it works!?

2 Answers2

0

Because your controller action only has the FunwarsVM model in the parameters, then it will never be binded correctly unless it is part of FunwarsVM object, which is why it works when you utilize the model.

if you add a new parameter List<IFormFile> images, then it should work as expected. Don't quote me on the way to define the parameter, but I believe it needs to have the same name as the name attribute to get automatically binded.

EDIT

Add the second parameter so that there is something to bind it to.

[HttpPost]
public async Task<IActionResult> Add(FunwarsVM model, List<IFormFile> images)
{
    model.Add();
    return RedirectToAction("Index",model);
}
bdparrish
  • 3,216
  • 3
  • 37
  • 58
0

For some unknown reason ASP.NET Core doesn't bind file to a nested object if you pass only one property for it (Images in your case). So the solution is just add any other property of that class to view

<input type="hidden" name="files.id" />
<input type="file" name="files.images" value="@Model.Files.Images" multiple />
Alexander
  • 9,104
  • 1
  • 17
  • 41