【问题标题】:Display all the contents in the Database Table in a html page?在 html 页面中显示数据库表中的所有内容?
【发布时间】:2019-12-30 11:29:47
【问题描述】:

我需要将数据库中的所有记录显示到 HTML 页面。

@model QBKartMVC.Models.Products

@foreach (var item in Model)
            {
                 <tr>    
                    <td><input type="checkbox"></td>
                    <td>@Html.DisplayFor(x => x.ProductCode)</td>
                    <td>@Html.DisplayFor(x => x.ProductName)</td>
                    <td>@Html.DisplayFor(x => x.ProductDes)</td>
                    <td>@Html.DisplayFor(x => x.ActiveFlag)</td>
                    <td>@Html.DisplayFor(x => x.Price)</td>
                 </tr>
             }

表达式树可能不包含动态操作是错误显示

public IActionResult Index()
        {
            var context = new DBContext();
            return View(context.Products.ToList());
        }

这是控制器部分

【问题讨论】:

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


【解决方案1】:

如下更新您的视图代码,

@model List<QBKartMVC.Models.Products>


@for (var i = 0; i < Model.Count; i++)
{
     <tr>    
       <td><input type="checkbox"></td>
       <td>@Html.DisplayFor(x => x[i].ProductCode)</td>
       <td>@Html.DisplayFor(x => x[i].ProductName)</td>
       <td>@Html.DisplayFor(x => x[i].ProductDes)</td>
       <td>@Html.DisplayFor(x => x[i].ActiveFlag)</td>
       <td>@Html.DisplayFor(x => x[i].Price)</td>
     </tr>
}

【讨论】:

  • 你必须从控制器传递产品列表
【解决方案2】:

你必须像这样创建 IEnumerable List

@model IEnumerable<QBKartMVC.Models.Products>

       @foreach (var item in Model)
        {
             <tr>    
                <td><input type="checkbox"></td>
                <td>@Html.DisplayFor(x => x.ProductCode)</td>
                <td>@Html.DisplayFor(x => x.ProductName)</td>
                <td>@Html.DisplayFor(x => x.ProductDes)</td>
                <td>@Html.DisplayFor(x => x.ActiveFlag)</td>
                <td>@Html.DisplayFor(x => x.Price)</td>
             </tr>
         }

【讨论】:

    【解决方案3】:

    @model List<QBKartMVC.Models.Products>
    
    @foreach (var item in Model)
                {
                     <tr>    
                        <td><input type="checkbox"></td>
                        <td>item.ProductCode</td>
                        <td>item.ProductName</td>
                        <td>item.ProductDes</td>
                        <td>item.ActiveFlag</td>
                        <td>item.Price</td>
                     </tr>
                 }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 2016-01-25
      相关资源
      最近更新 更多