2012-11-23 25 views
1

我有一个自定义类学生如下:转换自定义类对象IEnuerable其在foreach语句使用

 public class Student 
    { 
     public string Name {get;set;} 
     public string GuardianName {get;set;} 
    } 

现在,我的数据在以下数据结构

 IList<Student> studInfo=new List<Student>(); 

我来了已经把这个数据在viewbag

 Viewbag.db=studInfo; 

在视图页面,当我尝试使用

<table> 
     <thead> 
      <tr> 
       <td>Name</td> 
       <td>Guardian Name</td> 
      </tr> 
     </thead> 

    @foreach(var stud in ViewBag.db) 
    { 
      <tr> 
       <td>@stud.Name</td> 
       <td>@stud.GuardianName</td> 
      </tr> 

    } 
    </table> 

有一个错误,说

Cannot implicitly convert type 'PuneUniversity.StudInfo.Student' to 'System.Collections.IEnumerable' 

PuneUniversity是我的命名空间和StudInfo是应用程序的名称。请给我一个解决方案。 在此先感谢

+0

这看起来* *就像你做正确的事Darin指出的问题除外。您确定您提供的代码正是您在失败的解决方案中获得的代码吗? –

+0

为什么不试试列表 studInfo = new列表(); – series0ne

+0

啊...另一件事是,ViewBag.db是动态的(我认为...),因此,它可能不知道在你的foreach循环中,ViewBag.db的类型为列表,因为它被读为动态,因此,你可以尝试执行一个明确的演员? – series0ne

回答

1

下面一行是不可能编译:

IList<Student> studInfo = new IList<Student>(); 

不能创建的接口实例。所以我猜你的实际代码与你在这里显示的代码不一样。

另外我想使用强类型的意见,而不是ViewBag的建议你:

public ActionResult SomeAction() 
{ 
    IList<Student> students = new List<Student>(); 
    students.Add(new Student { Name = "foo", GuardianName = "bar" }); 
    return View(students); 
} 

,现在使你的观点强类型:

@model IEnumerable<Student> 

<table> 
    <thead> 
     <tr> 
      <th>Name</th> 
      <th>Guardian Name</th> 
     </tr> 
    </thead> 
    <tbody> 
    @foreach(var stud in Model) 
    { 
     <tr> 
      <td>@stud.Name</td> 
      <td>@stud.GuardianName</td> 
     </tr> 
    } 
    </tbody> 
</table> 
+0

除COM之外:) –

+0

谢谢...你可以建议我把类属性放在表中。也就是说,我不想手动编写数据,而是希望从类属性名称中呈现它。 –

相关问题