【问题标题】:Create a table with model in ASP.NET Core MVC在 ASP.NET Core MVC 中使用模型创建表
【发布时间】:2020-10-24 18:10:35
【问题描述】:

我正在尝试在我的视图中使用模型中的值构建一个表。我在 foreach 循环中的模型为空。我的控制器中是否缺少某些东西?

我的视图 (cshtml)

@model IEnumerable<MyApp.Models.BookModel>
@{
  ViewData["Title"] = "Index";
}

<table>
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.bookName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Author)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach(var b in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => b.bookName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => b.Author)
                </td>
            </tr>
        }
    </tbody>
</table>

谢谢!

【问题讨论】:

  • 您能否提供有关控制器中操作的更多详细信息?

标签: asp.net-core model-view-controller razor foreach null


【解决方案1】:

我测试了视图,没问题。所以恐怕你没有将数据从控制器传递到视图,或者你传递的数据为空。这是一个演示: 控制器:

public ActionResult Book()
        {
            List<BookModel> list = new List<BookModel> { new BookModel { bookName = "book1", Author = "author1" }, new BookModel { bookName = "book2", Author = "author2" }, new BookModel { bookName = "book3", Author = "author3" } };
            return View(list);
        }

查看:

@model IEnumerable<BookModel>
@{
    ViewData["Title"] = "Book";
}

<h1>Book</h1>

<table>
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.bookName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Author)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var b in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => b.bookName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => b.Author)
                </td>
            </tr>
        }
    </tbody>
</table>

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2012-04-09
    • 2019-11-28
    • 2022-01-06
    相关资源
    最近更新 更多