【问题标题】:ASP.NET using foreach to populate table is creating empty <td>ASP.NET 使用 foreach 填充表正在创建空 <td>
【发布时间】:2021-12-20 17:35:57
【问题描述】:

我正在学习 ASP.NET MVC 5,并且正在学习如何使用我使用数据库创建的数据填充表。我看到数据填充得很好(见下图),但第二列没有正确填充。

更新的图像

我不知道如何设置表格的样式,以免发生这种情况。这就是我需要你帮助的地方。

这就是我的 Index.cshtml:

@model IEnumerable<Vidly.Models.Customer>

@{
    ViewBag.Title = "Customers";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@ViewBag.Title</h2>

<div class="table-responsive">
    <table id="customers" class="table table-bordered table-hover">
        <thead>
        <tr>
            <th>Customer</th>
            <th>Discount Rate</th>
        </tr>
        </thead>
        <tbody>
        @foreach (var customer in Model)
        {
            <tr>
                <td>@Html.ActionLink(customer.Name, "Details", "Customers", new {id = customer.Id}, new {@class = ""})<td>
                <td>@customer.MembershipTypes.DiscountRate<td>
            </tr>
        }
        </tbody>
    </table>
</div>
<script>
    $('#customers tr').each(function() {
        if ($(this).children('td:empty').length === $(this).children('td').length) {
            $(this).remove(); // or $(this).hide();
        }
    });
</script>

这是 _Layout.cshtml,其中“部分视图”被引用:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @Html.Partial("_NavBar")
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - Vidly</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/lib")
    @RenderSection("scripts", required: false)
</body>
</html>

如果我缺少任何东西,请告诉我,我将提供帮助解决此问题所需的所有反馈。非常感谢。

【问题讨论】:

  • 你用另一个 结束 foreach 循环中的第一个 ,而不是 。
  • @VDWWD 感谢您的及时回复。请参阅我更新的消息。进行更改后,我的表中多了一些空的 。想法?
  • 同样的问题,你还在用&lt;td&gt;而不是&lt;/td&gt;
  • @RoryMcCrossan 你说的太对了。看我的回答

标签: html jquery css asp.net razor


【解决方案1】:

好的,感谢 VDWWD 的建议,我设法解决了我的问题。我只对我的表格 cshtml 文件做了一些调整:

    <table id="customers" class="table table-bordered table-hover"> 
<tr>
    <th>Customer</th>
    <th>Discount Rate</th>
</tr>

@foreach (var customer in Model)
{
    <tr>
        <td>@Html.ActionLink(customer.Name, "Details", "Customers", new {id = customer.Id}, new {@class = ""})</td>
        <td>@customer.MembershipTypes.DiscountRate</td>
    </tr>
}

</table>

问题是我没有为第一个数据输入关闭 foreach 循环。所以,我自然而然地(无意中)创建了那些空元素。

正如我之前所说,我正在学习这个令人惊叹的框架的来龙去脉。它真的很有趣。我希望这个答案可以帮助其他可能遇到这个问题的人。

再次感谢您。

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签