1

Here is my controller:

[HttpGet("")]
public IActionResult Index()
{
   ViewBag.showMonster =  _context.Monsters.ToList();
            
    return View();
}

and here is my cshtml:

<h1>@ViewBag.showMonster</h1>

Is this the wrong syntax? My view is showing:

System.Collections.Generic.List1[PracticeEntity.Models.Monster]

instead of the the actual row from my db.

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
aquile hollins
  • 161
  • 1
  • 8

3 Answers3

1

Use foreach to loop the object list item in the view.

 @foreach(var item in ViewBag.showMonster )
  {            
      <tr>    
        <td>@item.Name</td>
      </tr>        
  }
Thomson Mixab
  • 657
  • 4
  • 8
  • Thank you! Just curious, why didn't what I had work? do I have to do a loop anytime I want to show something? – aquile hollins Aug 06 '21 at 01:49
  • If you have a collection, array, or list. You will need a loop. The program will not able to guess how you want the list item to be display. – Thomson Mixab Aug 06 '21 at 04:02
0

I would recommend to use strongly typed view instead of using the ViewBag. It would make your code cleaner and easy to maintain.

public IActionResult Index()
{
    return View(_context.Monsters.ToList());
} 

In the view:

@model IList<Monster>

@foreach(var item in Model)
{
      @Html.DisplayFor(m => item) <br />
}

Why not to use ViewBag heavily?

ViewBag vs Model, in MVC.NET

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
0

Just traverse the List data in your database and take it out. I wrote some data:

Controller:

 public IActionResult Index()
        {
            List<Test> test = new List<Test>()
            {
                new Test{id=1,name="test1"},
                  new Test{id=2,name="test2"},
                    new Test{id=3,name="test3"},

            };
            return View(test);
        }

View:

@model IList<WebApplication69.Models.Test>

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

Result:

enter image description here

Tupac
  • 2,590
  • 2
  • 6
  • 19