【问题标题】:MVC Razor Var dataMVC Razor Var 数据
【发布时间】:2011-09-12 06:53:52
【问题描述】:

嗨,我是 MVC3 Razor 的新手。

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

在控制器中我将代码编写为

            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 =@tm.EmpName; 
                     // 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'". 

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

【问题讨论】:

  • 为什么不直接使用强类型模型?

标签: linq asp.net-mvc-3 razor var


【解决方案1】:

很遗憾,匿名对象不适用于视图。要么你需要返回一个非匿名来查看,要么返回一个动态对象来查看。

参考:http://rhizohm.net/irhetoric/post/2011/05/25/Taking-The-M-out-of-MVC-JSON-The-dynamic-Keyword-LINQ-.aspx

【讨论】:

    【解决方案2】:

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

    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:

    var test1 = 
        from ed in db.EmpDetails
        join dp in db.Departments on ed.EmpDept equals dp.DeptId
        select ed;
    return View(test1); 
    

    在视图内部:

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

    【讨论】:

      【解决方案3】:

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

          Like
      

      var test = (from p in db.EmpDetails orderby p.EmpName 升序选择 p).ToList(); ViewBag.test = 测试;

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

      谢谢....

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多