sly_Chandan
sly_Chandan

Reputation: 3515

MVC gives a strange error

The error message I'm getting is:

The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[MvcApplication1.ContentPageNav]', but this dictionary requires a model item of type 'MvcApplication1.ContentPageNav'.

public ActionResult Edit()
{
   DataClasses1DataContext dc = new DataClasses1DataContext();
   var model = from m in dc.ContentPageNavs
      select m;
   return View(model);
}

Any ideas on why I get this error? Any help will be appreciated.

Upvotes: 3

Views: 126

Answers (5)

Jonathan
Jonathan

Reputation: 2358

Have a look at your view it is strongly typed. It should say something like

Inherits="System.Web.Mvc<ContentPageNav>"

if you need a list you may want to consider using

Inherits="System.Web.Mvc<IList<ContentPageNav>>"

or some kind of list ... your LINQ might be wrong though if this is not intended.

Upvotes: 2

Andrew Orsich
Andrew Orsich

Reputation: 53685

Try this(your code does not work because of you view wait for ContentPageNav item but you send a list of ContentPageNav):

public ActionResult Edit()
{
   using(DataClasses1DataContext dc = new DataClasses1DataContext())
   {
     // here you can select some specific item from the ContentPageNavs list
     // Following query take first item from the list
     var model = dc.ContentPageNavs.FirstOrDefault();
     return View(model);
   }
}

Upvotes: 2

David Ruttka
David Ruttka

Reputation: 14409

It looks like your page is expecting a single ContentPageNav, not a LINQ expression. Try

return View(model.FirstOrDefault());

or

var model = dc.ContentPageNavs.FirstOrDefault();

Upvotes: 4

marcind
marcind

Reputation: 53183

As the error indicates the types don't match. The view expects a single item but you are passing in a collection of items. Try passing this in as the model : (from m in dc.ContentPageNavs select m).FirstOrDefault();

Upvotes: 2

Oded
Oded

Reputation: 499002

You are selecting a list of ContentPageNav into your model variable.

The view is expecting a ContentPageNav, not a list of them.

Try this:

var model = (from m in dc.ContentPageNavs
  select m).FirstOrDefault();

Upvotes: 6

Related Questions