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

3

我正在创建一个强类型视图。我的模型名为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>

当我运行网站时,在“@foreach (var item in Model)”这一行中,Model对象被突出显示,并且提示“对象引用未设置为对象的实例”的空指针异常。

我并不真正理解这段代码为什么会有问题,因为它并不是我写的,是Visual Studio生成的。这里发生了什么?


你能展示控制器动作代码返回这个视图吗?你的模型应该在那里被实例化。 - Ivan Gritsenko
你的 Controller 是什么样子的?你是否从你的 Home Controller 传递任何 IEnumrable<RestaurantView> - Ian
2个回答

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);
}

然而,模型应该从数据库中正确地填充。如果您可以粘贴您的控制器代码,那会很有帮助。

2

您的控制器应该传递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异常了


我知道我做错了。我忘记在“return View()”中包含参数。当我将其更改为“return View(model)”时,它起作用了。谢谢! - jimboweb
@jimboweb 太好了! ;) 是的,那通常是问题所在... - Ian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接