Search code examples
c#asp.net-mvclistmodels

Assigning model as list C#


enter image description here Why doesn't my list files get any values? I have another page with same logic and everything works fine.

I can provide more code if needed.

public ActionResult TestPDF(List<int> fileid)
    {

        List<object> myModel = new List<object>();
        List<object> obj = new List<object>();

        foreach (var id in fileid)
        {          
            obj.Add(db.UploadedFiles.Find(id));
        }
        myModel.Add(obj);

        return View(myModel);
    }

Solution

  • Sorry I wasn't careful enough in your snapshot. You Model is a collection of IEnumerable<UploadedFile>, so the [0] is indeed needed to get the first IEnumerable<UploadedFile>. So what you need to do is:

    List<Upload.Models.UploadedFile> files = Model.ToList()[0].ToList();
    

    Or you could just enum the files like:

    @foreach (var item in Model.ToList()[0])
    {
        ...
    }
    

    EDIT: A better way is to modify your controller so that it returns strong typed model, and get rid of the unnecessary nested List:

    public ActionResult TestPDF(List<int> fileid)
    {
    
        var myModel = new List<UploadedFile>();
    
        foreach (var id in fileid)
        {          
            myModel.Add(db.UploadedFiles.Find(id));
        }
    
        return View(myModel);
    }
    

    Then you could modify the @model in your view to

    @model List<Upload.Models.UploadedFile>
    

    And loop the files by

    @foreach (var item in Model)
    {
        ...
    }
    

    EDIT 2 Assuming you are using Entity Framework, you could refine the controller further more to:

    public ActionResult TestPDF(List<int> fileid)
    {
        List<Upload.Models.UploadedFile> myModel = fileid == null ? new List<Upload.Models.UploadedFile>() : db.UploadedFiles.Where(o => fileid.Contains(o.ID)).ToList();
    
        return View(myModel);
    }