使用Visual Studio和C#从ASP页面列出模型

时间:2014-10-08 15:42:31

标签: c# asp.net razor

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

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

在Employee命名空间中。当我为此模型创建Controller时,将创建默认的Create,Read,Update和Delete方法。还会创建一个索引页面,该页面在第一次加载时显示,此页面显示当前在数据库中的每个Employee。 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上显示一个基本菜单,并链接到包含所有Employees表的ViewAll页面。问题是它说“对象引用未设置为对象的实例”。并且不显示页面。我不明白为什么这段代码适用于Index.cshtml但不适用于ViewAll.cshtml,有人有建议吗?以下是一些教程的链接:http://www.asp.net/mvc/tutorials/mvc-5/introduction/accessing-your-models-data-from-a-controller

感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

只是为了清除这个问题,来自EmployeeController.cs,其中返回了与ViewAll页面关联的View。当ViewAll函数看起来像这样:

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

无法访问员工列表

@model IEnumerable<AnotherWebApp.Models.Employee>

为null。此函数的正确版本为:

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

现在可以访问所有Employees的列表,并且可以在ViewAll页面上轻松显示。 希望这对某人有所帮助,如果有人有更深层次的问题请询问!!