2013-04-05 42 views
0

我有一个页面,用户可以输入他们的状态信息,然后其他用户列表返回到状态中。我正在使用一个foreach循环。MVC 3在视图模型中接受null foreach

某些州有0个用户,这会导致我得到一个错误:未将对象引用设置为对象的实例。我怎么能通过这个错误?我正在使用的特定模型称为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 
} 
} 

当我不设置到对象的一个实例对象引用错误,行@if (Model.profile != null)突出显示,所以我尝试了要做到这一点:

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

但它没有奏效。任何想法如何接受一个空的模型在foreach或只是在运行时跳过代码?

回答

0

Profile是一个列表。看看列表是否有任何元素。

见,如果这个工程:

@if (Model.profile.Any()) 
{ 
    foreach (var item in Model.profile) 
    {  
     @item.city 
    } 
} 
+1

如果列表为空,则foreach循环不应该崩溃;它应该只循环0次。它看起来像模型本身是空的,给出错误和奇怪的控制器代码。 – 2013-04-09 15:45:46

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),让它空收集和留在这一点。

要变成全圆形,只要变量填充了某种类型的集合(空或填充),就不应该打破。它只会跳过代码块而不输出任何内容。如果你得到一个对象为空的错误,这很可能是因为变量是空的,并且不能检索枚举器。