无法在剃刀视图中使用LINQ方法ASP.Net

时间:2019-01-10 01:47:39

标签: c# asp.net-mvc linq razor model

我在view.cshtml中这样调用模型:

@model IEnumerable<Spiirit_Project.Models.Deliverable>

然后我在view.cshtml中使用这种LINQ方法:

@{ var a = Model.Where(p => p.deliverable_research_year_id == 169).Count(); }

运行项目时,出现错误: “值不能为空。 参数名称:source”。

我的“可交付成果”表不为空,但出现此错误。如何解决此错误?

有我的控制器:

public ActionResult CreateDeliverable(int? idResearch, int? idBaseline, int? idYear){
ViewBag.IdResearch = idResearch;
ViewBag.IdBaseline = idBaseline;
ViewBag.IdYear = idYear;
ViewBag.Year = db.Deliverable_Research_Years.Find(idYear);
ViewBag.Deliverable = db.Deliverables.ToList();

return View();
}

2 个答案:

答案 0 :(得分:3)

@mjwills在评论中告诉我,以将模型传递给视图。所以我这样更改控制器:

public ActionResult CreateDeliverable(int? idResearch, int? idBaseline, int? idYear){
ViewBag.IdResearch = idResearch;
ViewBag.IdBaseline = idBaseline;
ViewBag.IdYear = idYear;
ViewBag.Year = db.Deliverable_Research_Years.Find(idYear);

return View(db.Deliverables.ToList());
}

这正常工作!

答案 1 :(得分:-2)

尝试

@{ var a = Model?.Where(p => p.deliverable_research_year_id == 169).Count() ?? 0; }

这是假设deliverable_research_year_id不是可为空的类型。