【问题标题】:How do I show the results of information from my database to my view using viewBag?如何使用 viewBag 将我的数据库中的信息结果显示到我的视图中?
【发布时间】:2021-08-06 01:36:31
【问题描述】:

这是我的控制器:

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

这是我的cshtml

<h1>@ViewBag.showMonster</h1>

这是错误的语法吗? 我的观点正在显示:

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

而不是我数据库中的实际行。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-core


    【解决方案1】:

    使用 foreach 循环视图中的对象列表项。

     @foreach(var item in ViewBag.showMonster )
      {            
          <tr>    
            <td>@item.Name</td>
          </tr>        
      }
    

    【讨论】:

    • 谢谢!只是好奇,为什么我没有工作?每当我想展示一些东西时,我是否必须循环播放?
    • 如果你有一个集合、数组或列表。您将需要一个循环。程序将无法猜测您希望列表项如何显示。
    【解决方案2】:

    我建议使用强类型视图而不是使用ViewBag。它将使您的代码更简洁且易于维护。

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

    在视图中:

    @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

    【讨论】:

      【解决方案3】:

      只需遍历数据库中的List数据并取出即可。我写了一些数据:

      控制器:

       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);
              }
      

      查看:

      @model IList<WebApplication69.Models.Test>
      
      @foreach(var item in Model)
                  {
      <div> @item.name</div>
                  }
                 
      

      结果:

      【讨论】:

        猜你喜欢
        • 2021-10-16
        • 2017-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-08
        相关资源
        最近更新 更多