Search code examples
asp.netasp.net-mvcviewcontrollermodels

Error loading images from database


I have a question about showing images loaded from a mysql database in an Index view.

In my database table "deliverables" I have "item_id", "deliverable_image" and "afstudeerrichting_id". "item_id" and "afstudeerrichting_id" are FK from other tables.

I want to show the images when afstudeerrichting_id = ..

Controller:

public ActionResult Index()
{
    var model = repository.GetIdsOfImages(1);
    return View(model.ToList());
}

public ActionResult ShowImage(int id)
{
    IQueryable<byte[]> data = repository.GetImages(id);
    byte[] firstimage = data.First();

    return File(firstimage, "image/png");
}

Repository:

public IQueryable<long> GetIdsOfImages(int afstudeerrichtingid)
{
    return from deliverable in entities.deliverables
           where deliverable.afstudeerichting_id.Equals(afstudeerrichtingid)
           select deliverable.item_id;
}
public IQueryable<byte[]> GetImages(int itemID)
{
    return from deliverable in entities.deliverables
           where deliverable.item_id.Equals(itemID)
           select deliverable.deliverable_image;
}

View:

@foreach(var imgID in Model.DeliverablesIDsList)
{
    <img src="@Url.Action("ShowImage", "Deliverable", new { DeliverableID = imgID })" />
}

In my Viewmodel I have:

public List<long> DeliverablesIDsList { get; set; }
public int DeliverableID { get; set; }

But now I always get this error:

he model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Int64]', but this dictionary requires a model item of type 'GDMfrontEnd.Models.DeliverableViewModel'.

Does someone knows what I'm doing wrong?


Solution

  • you're sending to the view a list of int64 repository.GetIdsOfImages(1).ToList() and the view requires a DeliverableViewModel, so you must create a model and put the list into the model and send it to the view

    the action should looks like:

    public ActionResult Index()
    {
        var model = repository.GetIdsOfImages(1);
        DeliverableViewModel model = new DeliverableViewModel()
        model.DeliverablesIDsList = repository.GetIdsOfImages(1).ToList();
        return View(model); //send to the view a model type of DeliverableViewModel
    }
    

    now with ActionResult ShowImage, the action expect id parmeter and you're sending DeliverableID, so change de var name

    public ActionResult ShowImage(int DeliverableID)
    {
        IQueryable<byte[]> data = repository.GetImages(DeliverableID);
        byte[] firstimage = data.First();
    
        return File(firstimage, "image/png");
    }