首页 > 解决方案 > 你调用的对象是空的。发送数据时出现异常哟通过viewmodel查看

问题描述

当我尝试运行视图时,它在这一行中给出了上述异常

@model ClothBazar.Web.ViewModels.HomeViewModels

@{ ViewBag.Title = "主页"; var firstCategory = Model.Categories.Where(x => x.ImageURL != null).First(); //它正在获取firstcategory中的空值}

虽然我的表中已经有数据 在此处输入图像描述

HomeViewModels 类的代码

    public class HomeViewModels
{
    public List<Category> Categories { get; set; }
    public List<Product> Products { get; set; }
}

类别代码

    public class Category : BaseEntities
{
    public string ImageURL { get; set; }
    public List<Product> Products { get; set; }
}

主页 索引操作

  CategoryService categoryService = new CategoryService();
    public ActionResult Index()
    {
        HomeViewModels model = new HomeViewModels();
        model.Categories = categoryService.GetCategories();
        return View();
    }

无法弄清楚为什么 var firstCategory 没有获得任何价值

标签: asp.net-mvcentity-frameworklinq

解决方案


在查看您的代码时,您需要更新您的代码部分。在您正在访问的 View 页面上,HomeViewModels这是 ViewModel。因此,如果您想获取Categories您在其上循环的值,因为它是列表类型。

@{ ViewBag.Title = "Home Page";     
Foreach(var category in Model.Categories ) 
{
   //Access your value inside this or bind you html code here
}    
}

我希望这个方向会对你有所帮助。


推荐阅读