.net强类型视图模型未设置为对象的实例

时间:2016-03-19 14:40:47

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

所以我正在创建一个强类型视图。我的模型叫做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基于此创建了一个强类型的List模型,如下所示:

@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>

当我运行网站时,我在行&#34; @foreach(模型中的var项目)&#34;中突出显示模型对象,并声明&#34;对象引用未设置为一个对象的实例。&#34;

并不真正理解这段代码是如何出错的,因为我甚至没有写它,Visual Studio做到了。这里发生了什么?

2 个答案:

答案 0 :(得分:2)

听起来你还没有在Controller内正确地实例化你的模型。

作为测试你可以试试这个:

public ActionResult Reviews()
{
   var model = new List<OdeToFood.Models.RestaurantReview>();
   model.Add(new OdeToFood.Models.RestaurantReview { Name = "Test" });
   model.Add(new OdeToFood.Models.RestaurantReview { Name = "Test2" });

   return View(model);
}

但是,应该从DB正确填充模型。如果您可以粘贴有用的控制器代码。

答案 1 :(得分:2)

您的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例外