【问题标题】:MVC 3 accept null foreach in the viewModelMVC 3 在 vi​​ewModel 中接受 null foreach
【发布时间】:2023-04-11 05:14:01
【问题描述】:

我有一个页面,用户可以在其中输入他们的状态信息,然后返回该状态中的其他用户列表。我正在使用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  
 }
}

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

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

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

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 model foreach


    【解决方案1】:

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

    看看这是否有效:

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

    【讨论】:

    • 如果列表为空,foreach 循环不应崩溃;它应该只循环 0 次。考虑到错误和奇怪的控制器代码,看起来模型本身是空的。
    【解决方案2】:

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


    馆藏跟进

    我一直发现,只要您有实现IEnumerable&lt;T&gt; 的变量,最好用一个空集填充它,而不是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 &amp;&amp; variables.Count() &gt; 0),否则请将其设为空集合并留在那里。

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

    【讨论】:

      猜你喜欢
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 2019-08-11
      相关资源
      最近更新 更多