Search code examples
c#asp.net-mvclinqlistboxviewbag

ViewBag on ListBox gets empty data


I made a LINQ Statement to fill a ViewBag and display it on my View, however for some reason my ListBox displays empty so i saved the LINQ statement on a txt file to see if it was empty, but it has the correct data, so my question is:

Why my ViewBag is not Displaying on my ListBox in my View?

This is my Linq Filling the ViewBag:

foreach (var item in db.VENTA_PLATILLOS
                       .Select(v => new { Turno = v.Nombre_Turno, Total = v.Total })
                       .GroupBy(l => l.Turno)
                       .AsEnumerable()
                       .Select(z => new { Turno = z.Key, Total = String.Format("{0:$#,##0.00;($#,##0.00);Zero}", Decimal.Round(z.Sum(l => l.Total), 0)) })
                       .OrderByDescending(a => a.Turno))

{
    listadesumas.Add(string.Format("{{{0}, Total = {1}}}", item.Turno, item.Total));
}

//txt file to see if Linq Statemnt is filled correctly and it is
var json5 = JsonConvert.SerializeObject(listadesumas);
System.IO.File.WriteAllText(@"C:\inetpub\wwwroot\SumasTurno.txt", json5);

//Filling my Viewbag with my LinQ Group By Result
var grupos = new SelectList(listadesumas.ToList());
ViewBag.Group = grupos;

This is my View ListBox:

@{
    var group = (SelectList)ViewBag.Group;
 }

@Html.ListBox("Group", (IEnumerable<SelectListItem>)ViewBag.Group, new { style = "width: 300px;" })

Solution

  • Try the following in your controller instead...

    ViewBag["Group"] = grupos;
    

    ...and this in the view...

    @Html.ListBox("Group", (IEnumerable<SelectListItem>)ViewBag["Group"], new { style = "width: 300px;" })