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.
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();
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();
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);
}
}
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();
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.
精彩评论