ASP.NET CORE Error when trying to add a List of Objects to an Object with a list in it

I have a ASP.Net Core project that I’m working on. So I have a Linq call that gets the information from the database and sends it back to the Controller, no problem there. When I send this data to the View I get an error

The model item passed into the ViewDataDictionary is of type ‘System.Collections.Generic.List`1[PhotoUploader.Models.UnitPictures]’, but this ViewDataDictionary instance requires a model item of type ‘PhotoUploader.Models.FileViewModel’.

Now I know why this is, Its because the model types don’t match from the controller to the View. My question is, how do I assign the UnitPictures to the FileViewModel list I’ve created inside of it.

Model

public class UnitPictures
{
    public long ImageId { get; set; }
    public string FileName { get; set; }
    public string FileLocation { get; set; }
    public int SortOrder { get; set; }
}

View Model

public class FileViewModel 
{
    public FileViewModel()
    {
        UnitPicturesList = new List<UnitPictures>();
    }
    //Other Fields here
    public List<UnitPictures> UnitPicturesList { get; set; }
}

Method Call return data of type UnitPictures

    private List<UnitPictures> GetImages(long Id)
    {
        var images = (from a in _db.Images
                      join b in _db.AutoImage 
                        on  a.ImageId equals b.ImageId
                      where b.Id == Id
                      select new UnitPictures
                      {
                         FileLocation = "",
                         FileName = a.FileName,
                         SortOrder = 0, 
                         ImageId = a.ImageId

                      }).ToList();

        return images;
    }

Controller

    public IActionResult UnitImages(long Id, long unitId)
    {           
        var images = GetImages(Id);           

                  
        return View(images);
    }

View

 @model FileViewModel

 <div class="row">
  <div class="col-lg-4 col-md-12 mb-4 mb-lg-0">

 @for (var i = 0; i < Model.UnitPicturesList.Count; i++)
 {
    <img
      src="https://mdbcdn.b-cdn.net/img/Photos/Horizontal/Nature/4-col/img%20(73).webp"
      class="w-100 shadow-1-strong rounded mb-4"
      alt="Boat on Calm Water"
    />
 }
</div>

>Solution :

You create an instance of the view model, populate the relevant members and return that to the view.

public IActionResult UnitImages(long Id, long unitId)  
    var images = GetImages(Id);           
    FileViewModel model = new FileViewModel() {
        UnitPicturesList = images
    };                   
    return View(model);
}

The will allow the view to now properly bind to the matching members in the ViewDataDictionary

Leave a Reply