1

I call a model in view.cshtml like this:

@model IEnumerable<Spiirit_Project.Models.Deliverable>

Then I use this LINQ-method in view.cshtml so:

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

When I run my project, there is error: "Value cannot be null. Parameter name: source".

my "Deliverable" Table is not null but I get this error. How to fix this error?

there is my controller:

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();
}
Aghnat Atqiya
  • 275
  • 5
  • 18
  • 1
    Your model *is* null, regardless of your claim. If you want to prove us wrong, add a screenshot of the Visual Studio debugger with the value of Model. – Camilo Terevinto Jan 10 '19 at 02:04
  • Please add the controller code **to your question** (not in comments). – mjwills Jan 10 '19 at 02:17
  • `return View(db.Deliverables.ToList());` - and no need to assign to `ViewBag.Deliverable`. Then have a read of https://stackoverflow.com/questions/6242810/why-is-the-view-model-null . – mjwills Jan 10 '19 at 02:18
  • It is better to use `Model` than `ViewBag` - https://stackoverflow.com/questions/21716953/viewbag-vs-model-in-mvc-net – mjwills Jan 10 '19 at 04:32
  • Best practice is **not** `ViewBag`. Read the link I provided. If you need multiple objects, then create your own `AghnatModel` class with multiple properties (for each of things you need). Then use `@model Spiirit_Project.Models.AghnatModel`. – mjwills Jan 10 '19 at 04:41

2 Answers2

3

@mjwills tell me in comment to pass in the model to the view. So I change my controller like this:

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

This is work correctly!

Aghnat Atqiya
  • 275
  • 5
  • 18
-2

Try

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

This is assuming that deliverable_research_year_id is NOT a nullable type.

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73