MVC给出了一个奇怪的错误

时间:2011-02-24 16:36:04

标签: c# asp.net-mvc linq

我收到的错误消息是:

  

传递到字典中的模型项的类型为'System.Data.Linq.DataQuery`1 [MvcApplication1.ContentPageNav]',但此字典需要类型为'MvcApplication1.ContentPageNav'的模型项。

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

关于我为何会收到此错误的任何想法?任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:6)

您正在ContentPageNav变量中选择model列表

该视图需要ContentPageNav,而不是它们的列表。

试试这个:

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

答案 1 :(得分:4)

看起来您的页面需要单个ContentPageNav,而不是LINQ表达式。试试

return View(model.FirstOrDefault());

var model = dc.ContentPageNavs.FirstOrDefault();

答案 2 :(得分:2)

由于错误表明类型不匹配。视图需要单个项目,但您传递的是项目集合。尝试将其作为模型传递:(from m in dc.ContentPageNavs select m).FirstOrDefault();

答案 3 :(得分:2)

试试这个(你的代码不起作用,因为你查看等待ContentPageNav项目,但你发送了一个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);
   }
}

答案 4 :(得分:2)

看看你的观点是强类型的。它应该说像

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

如果您需要列表,可以考虑使用

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

或某种列表......如果不是这样,你的LINQ可能是错的。

相关问题