I want to get record from my db where hidden=false and id is got in browser. Please see my code and fix for me, thanks so much (I searched but can not fix my error). My action:
public ActionResult Detail(int id = 0)
{
var item = db.Destinations.Where(i=>i.Hidden==false && i.Id==id);
if (item==null)
{
return HttpNotFound();
}
return View(item);
}
My View:
@model vtt.Models.Destination
@{
ViewBag.Title = "Detail";
}
<div class="white">
<h1>@Model.Name</h1>
@Html.Raw(Model.Description)
</div>
And Error:
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery`1[vtt.Models.Destination]', but this dictionary
requires a model item of type 'vtt.Models.Destination'.
Currently you're trying to pass in a model which is a query, whereas your view is expecting a single model object. Currently your check for nullity is pointless, too - the result of Where
is never null
... it's just a query.
Instead, you should use SingleOrDefault
, which *executes the query, getting a single value:
var item = db.Destinations.SingleOrDefault(i => !i.Hidden && i.Id == id);
Now the check for nullity will be useful (because SingleOrDefault
will return null
if there are no results) and the type will be correct for the view.
See more on this question at Stackoverflow