Home > Software design >  ASP.NET Core 6.0 MVC - Populating a viewmodel from list
ASP.NET Core 6.0 MVC - Populating a viewmodel from list

Time:05-23

Currently I am dabbling in ASP.NET Core 6.0 and got stuck on trying to populate a view model.

I have the following linq(?) query (is it even called that?)

var fotoGeneratedNames = _context.Foto 
                                 .Where(x => fotoIds.Contains(x.Id))
                                 .Select(x => x.generatedName)
                                 .ToList();

Controller code

// Diese Methode gibt die notwendigen Daten für eine spezifische Gallerie zurück 
public IActionResult Gallerie(int id) 
{ 
    // instantiert neue Var mit dem Expose Viewmodel Gallerie
    // var viewModelExposeGallerie = new ViewModelExposeGallerie(); 

    // nimm gallerieId, such alle FotoIds aus associationtable raus
    var fotoIds = (from a in _context.GallerieFoto 
                   where a.GallerieId == id select a.FotoId).ToList();

    // Nimm alle elemente in der tabelle Foto mit den Elementen in fotoIds und mach eine Liste mit den generiertenNamen der Fotos
    var fotoGeneratedNames = _context.Foto
                                     .Where(x => fotoIds.Contains(x.Id))
                                     .Select(x => x.generatedName)
                                     .ToList();

    return View(fotoGeneratedNames);
}  

This is my view model

namespace abc.Models
{
    public class ViewModelExposeGallerie
    {
        public string FotoName { get; set; }    
    }
}

Now - what I tried was a foreach akin to

foreach var x in fotoGeneratedNames 
    ViewModelExposeGallerie.FotoName = fotoGeneratedNames 

but this only replaced the value and did not give me a list, that I could use in the view.

Thankful for any hints, have a good one!

CodePudding user response:

In your controller:

public IActionResult Gallerie(int id) { 

    ...
             
    var fotoGeneratedNames = _context.Foto
        .Where(x => fotoIds.Contains(x.Id))
        .Select(x => x.generatedName)
        .ToList();

    return View(fotoGeneratedNames);
}  

You are returning a List<string> but not List<ViewModelExposeGalleri> type

Your view should be as below:

@model IEnumerable<string>

@foreach (var name in Model)
{
    <div>@name</div>
}

Unsure what you want to render for the HTML element, so I illustrate the demo with <div> element.


If you return List<ViewModelExposeGalleri> from the Controller:

public IActionResult Gallerie(int id) { 

    ...
             
    var fotoGeneratedList = _context.Foto
        .Where(x => fotoIds.Contains(x.Id))
        .Select(x => new ViewModelExposeGallerie
        {
            FotoName = x.generatedName
        })
        .ToList();

    return View(fotoGeneratedList);
} 
@model IEnumerable<abc.models.ViewModelExposeGalleri>

@foreach (var item in Model)
{
    <div>@item.FotoName</div>
}
  • Related