asp.net-mvc - 你调用的对象是空的。发送数据时出现异常哟通过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 没有获得任何价值
解决方案
在查看您的代码时,您需要更新您的代码部分。在您正在访问的 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
}
}
我希望这个方向会对你有所帮助。
推荐阅读
- ios - 将 Html 字符串转换为属性字符串并分配给 textview 以获得额外的空间
- javascript - 三点符号在 js 本地存储中不起作用
- python - 在 python 中安装“Louvain”包时出错
- visual-studio-code - 如何使用深色编辑区域和浅色小部件自定义 VSCode?
- kotlin - Kotlin 中使用函数的意义何在
- php - 如何将 SQL 语句更改为 laravel 查询
- forms - 数组类型的预期参数,给定实体
- excel - VBA循环到下一行并突出显示工作表中的错误
- r - 用另一列的总和替换正在进行的 NA 值
- java - 使单例具有所有静态字段