【问题标题】:Cannot Use LINQ-Method In Razor View ASP.Net无法在 Razor 视图 ASP.Net 中使用 LINQ 方法
【发布时间】:2019-01-10 01:47:39
【问题描述】:

我在 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();
}

【问题讨论】:

  • 您的模型 null,无论您的声明如何。如果你想证明我们错了,添加一个带有 Model 值的 Visual Studio 调试器的屏幕截图。
  • 请将控制器代码添加到您的问题中(不在 cmets 中)。
  • return View(db.Deliverables.ToList()); - 无需分配给ViewBag.Deliverable。然后阅读stackoverflow.com/questions/6242810/why-is-the-view-model-null
  • 最好使用Model而不是ViewBag - stackoverflow.com/questions/21716953/…
  • 最佳实践是不是 ViewBag。阅读我提供的链接。如果您需要多个对象,则创建您自己的具有多个属性的AghnatModel 类(对于您需要的每一个东西)。然后使用@model Spiirit_Project.Models.AghnatModel

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


【解决方案1】:

@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());
}

这是正常工作!

【讨论】:

    【解决方案2】:

    试试

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

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

    【讨论】:

    • 这假设 OP 可以使用 C# 6+ 并且它没有解决任何问题,它只是隐藏了一个错误。
    猜你喜欢
    • 1970-01-01
    • 2016-03-22
    • 2011-12-09
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多