日期:2014-05-18  浏览次数:20909 次

MVC中如何构建类型IEnumerable<T>的模型项
接触MVC不久,在项目中遇到了下面的问题:

  有一张表Customers,我现在只想取出其中的一个字段ContactName在List页面展示出来,代码如下。

C# code

public ActionResult Index()
{
    var q = from c in ltdb.Customers select c.ContactName;

    return View(q);
}



  但是代码执行过程中会报错,错误如下。
传入字典的模型项的类型为“System.Data.Linq.DataQuery'1[System.String]”,但此字典需要类型“System.Collections.Generic.IEnumerable'1[MvcApplication3.Models.Customers]”的模型项。

  现在是不是需要将“from c in ltdb.Customers select c.ContactName”的结果转换成为“IEnumerable<T>”类型返回呢,

  如果是的话,怎么将其转换成为正确的模型项?

麻烦高手帮忙指点一下,不胜感激。

------解决方案--------------------
问题是你当前页面接收的类型是怎样的?
------解决方案--------------------
我没用过Linq,但是我觉得报的这个错误的原因是你定义的是IEnumerable<MvcApplication3.Models.Customers>和你赋值的是IEnumerable<string>是不对的。你把IEnumerable<MvcApplication3.Models.Customers>改成IEnumerable<string>试试。
------解决方案--------------------
类型选择错误吧?c.ContactName是什么类型的?返回的是什么类型?