0

我有一个页面,用户可以在其中输入他们的状态信息,然后其他用户的列表会返回该状态。我正在使用foreach循环。

一些州有 0 个用户,这导致我得到一个错误:Object reference not set to an instance of an object。我怎样才能克服这个错误?我使用的特定模型称为 Profiles。

该模型:

public class homepage
{
    public List<profile> profile { get; set; }
    public PagedList.IPagedList<Article> article { get; set; }
}

控制器:

public ActionResult Index()
{
    HttpCookie mypreference = Request.Cookies["cook"];
    if (mypreference == null)
    {
        ViewData["mypreference"] = "Enter your zipcode above to get more detailed information";
        var tyi = (from s in db.profiles.OrderByDescending(s => s.profileID).Take(5) select s).ToList();
    }
    else
    {
        ViewData["mypreference"] = mypreference["name"];
        string se = (string)ViewData["mypreference"];
        var tyi = (from s in db.profiles.OrderByDescending(s => s.profileID).Take(5) where se==s.state select s).ToList();
    } 
    return View();
}

风景:

@if (Model.profile != null)
{
 foreach (var item in Model.profile)
 {
  @item.city  
 }
}

当我得到Object reference not set to an instance of an object错误时,该行@if (Model.profile != null)被突出显示,所以我尝试这样做:

public List<profile>? profile { get; set; }

但它没有用。关于如何在 foreach 中接受空模型或只是在运行时跳过代码的任何想法?

4

2 回答 2

1

个人资料是一个列表。查看列表是否有任何元素。

看看这是否有效:

@if (Model.profile.Any())
{
   foreach (var item in Model.profile)
   {    
      @item.city  
   }
}
于 2013-04-05T20:26:53.203 回答
1

刚刚注意到,您正在调用View()但没有将模型传递给它,然后在您引用的视图中Model.profile。不可避免地Model为空,因此没有profile可访问的属性。确保将模型传递给return View(model)调用中的视图。


收藏品的跟进

我一直发现,任何时候你有一个实现的变量,IEnumerable<T>最好用一个空集填充它null。也就是说:

// no-nos (IMHO)
IEnumerable<String> names = null; // this will break most kinds of
                                  // access reliant on names being populated
                                  // e.g. LINQ extensions

// better options:
IEnumerable<String> names = new String[0];
IEnumerable<String> names = Enumerable.Empty<String>();
IEnumerable<String> names = new List<String>();

除非您喜欢在if (variable != null && variables.Count() > 0)每次想要访问它时检查它,否则请将其设为空集合并保留它。

完整地说,只要变量填充了某种类型的集合(空的或填充的),aforeach就不会中断。它只会跳过代码块而不输出任何内容。如果您收到对象空错误,很可能是因为变量为空并且无法检索到枚举数。

于 2013-04-09T15:51:01.033 回答