【问题标题】:Listing Models from ASP pages, with Visual Studio and C#使用 Visual Studio 和 C# 从 ASP 页面列出模型
【发布时间】:2014-10-09 15:19:59
【问题描述】:

我正在使用 Visual Studio 在 ASP 中创建一个非常基本的 Web 应用程序,我使用默认网站然后创建了“员工”模型。该模型可以使用以下方法存储在数据库中:

public class EmployeeDBContext : DbContext 
{
    public DbSet<Employee> Employees{ get; set; }
}

在员工命名空间中。当我为此模型创建控制器时,会创建默认的创建、读取、更新和删除方法。还创建了一个索引页面,该页面在第一次加载页面时显示,该页面显示当前在数据库中的每个员工。 Index.cshtml 的代码如下所示:

@model IEnumerable<AnotherWebApp.Models.Employee>
@{
    ViewBag.Title = "Index";
}

<h2>All Employee Options</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<p>
    @Html.ActionLink("View All", "ViewAll")
</p>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Role)
        </th>
        <th>
            <b>Options</b>
        </th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Role)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.ID })
            </td>
        </tr>
    }
</table>

我要做的是在 Index.cshtml 上显示一个基本菜单,并链接到包含所有员工表的 ViewAll 页面。问题是它说“对象引用未设置为对象的实例。”并且页面不显示。我看不出为什么此代码适用于 Index.cshtml 但不适用于 ViewAll.cshtml,有人有建议吗?这是一些教程的链接:http://www.asp.net/mvc/tutorials/mvc-5/introduction/accessing-your-models-data-from-a-controller

感谢您的建议。

【问题讨论】:

  • 您能否向我们展示实际产生错误的代码并指出错误发生在哪一行? NullReferenceException 很容易调试,只需在该行上放一个断点,调试时查看哪个对象是 null

标签: c# asp.net razor


【解决方案1】:

为了解决这个问题,这个问题来自 EmployeeController.cs,其中与 ViewAll 页面关联的视图被返回。当 ViewAll 函数看起来像这样时:

public ActionResult ViewAll()
{
    return View();
}

无法访问员工列表

@model IEnumerable<AnotherWebApp.Models.Employee>

为空。此函数的正确版本是:

    public ActionResult ViewAll()
    {
        return View(db.Employees.ToList());
    }

现在可以访问所有员工的列表,并且可以轻松地在 ViewAll 页面上显示。 希望这对某人有所帮助,如果有人有进一步的问题,请询问!

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多