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();
}
5
  • 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. Commented Jan 10, 2019 at 2:04
  • Please add the controller code to your question (not in comments). Commented Jan 10, 2019 at 2:17
  • return View(db.Deliverables.ToList()); - and no need to assign to ViewBag.Deliverable. Then have a read of stackoverflow.com/questions/6242810/why-is-the-view-model-null . Commented Jan 10, 2019 at 2:18
  • It is better to use Model than ViewBag - stackoverflow.com/questions/21716953/… Commented Jan 10, 2019 at 4: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. Commented Jan 10, 2019 at 4:41

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

Comments

-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.

1 Comment

This assumes that the OP can use C# 6+ and it doesn't solve any kind of problems, it just hides a bug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.