c# - .net 强类型 View 模型未设置为对象实例

标签 c# asp.net .net asp.net-mvc razor

<分区>

所以我正在创建一个强类型 View 。我的模型名为 RestaurantReview.cs,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace OdeToFood.Models
{
    public class RestaurantReview
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public int Rating { get; set; }
    }
}

我让 Visual Studio 基于此创建了一个强类型列表模型,如下所示:

@model IEnumerable<OdeToFood.Models.RestaurantReview>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Country)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Rating)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Country)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Rating)
        </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>

当我运行网站时,在“@foreach(模型中的变量项)”行中出现空指针异常,突出显示模型对象,并指出“对象引用未设置为对象的实例。”

我什至没有真正理解这段代码怎么会出错,因为我什至没有编写它,Visual Studio 做到了。这里发生了什么?

最佳答案

您的 Controller 节目已通过 RestaurantReview IEnumerable。示例:

public class HomeController : Controller { //suppose this is your Home
    public ActionResult Index() {
        IEnumerable<OdeToFood.Models.RestaurantReview> model;
        model = from m in db.RestaurantReviews
                ... //your query here
                select m;
        return View(model); //pass the model here
    }

那么你就不会得到null异常

关于c# - .net 强类型 View 模型未设置为对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36103055/

相关文章:

c# - 在c#中使用pc中的所有内核

c# - 'Enums' 类中不允许代码优先枚举? (英孚 5)

c# - 此操作会创建结构不正确的文档

c# - .NET 的嵌入式 awk?

c# - C# 中的属性

c# - 标签透明底色

c# - 在 .Net 中将 Html 转换为 Word

.net - 用户定义的 linq 过滤器

c# - OutOfMemoryException : Out of memory - System. Drawing.Graphics.FromImage

C#如何在文本框为空时防止按下Tab键