首页 > 解决方案 > ASP.NET 使用 foreach 填充表正在创建空

问题描述

我正在学习 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>

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

标签: htmljquerycssasp.netrazor

解决方案


好的,感谢 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 循环。所以,我自然而然地(无意中)创建了那些空元素。

正如我之前所说,我正在学习这个惊人框架的来龙去脉。它真的很有趣。我希望这个答案可以帮助任何可能偶然发现这个问题的人。

再次感谢你。


推荐阅读