2011-06-10 63 views
2

嗨,我是MVC3 Razor的新手。MVC Razor Var数据

我试图显示数据库表中的值。

在控制器我写的代码为

  var test1 = from ed in db.EmpDetails 
      join dp in db.Departments on ed.EmpDept equals dp.DeptId 
       select new 
       { 
        EmpId = ed.EmpId, 
        EmpName = ed.EmpName, 
        EmpDesignation = ed.EmpDesignation, 
        EmpSalary = ed.EmpSalary, 
        EmpUserName =ed.EmpUserName, 
        EmpDept =ed.EmpDept, 
        deptName = dp.deptName 
       }; 

     ViewBag.test = test1; 

,并在视图

   @foreach (var tm in ViewBag.test) 
       { 

        string abc [email protected]; 
        // and the logic 
       } 


Here i am getting all the value in the "tm" variable. But when i try to get the particular value of EmpName in a string it is showing the error as "'object' does not contain a definition for 'EmpName'". 

请帮我解决这个错误。 谢谢 san

+1

为什么不直接使用强类型的模型? – iwayneo 2011-06-10 07:24:08

回答

0

我可以如果我将linq结果转换为控制器中的toList(),可以获得视图中的值。

Like 

VAR测试=(从对在db.EmpDetails ORDERBY p.EmpName升序选择p)的.ToList(); ViewBag.test = test;

And in the view 

    @foreach (var tm in ViewBag.test) 
    { 
      int emId = @tm.id; 
    } 

感谢....

1

不能在视图中使用匿名对象。试试这样:

var test1 = 
    from ed in db.EmpDetails 
    join dp in db.Departments on ed.EmpDept equals dp.DeptId 
    select ed; 
ViewBag.test = test1; 

然后:

@foreach (var tm in (IEnumerable<Employee>)ViewBag.test) 
{ 
    string abc = tm.EmpName; 
    // and the logic 
} 

但我个人会使用强类型的意见,而不是ViewBag建议您:

​​

和视图里面:

@model IEnumerable<Employee> 
@foreach (var tm in Model) 
{ 
    string abc = tm.EmpName; 
    // and the logic 
}