MVC Razor 变量数据
您好,我是 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 [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'".
请帮助我解决此错误。 谢谢 桑
Hi i am new to MVC3 Razor .
I was trying to display the values from the database table.
in controller i wrote the code as
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;
and in the view
@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'".
Please help me to solve this error.
Thanks
san
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,匿名对象不能与视图一起使用。要么您需要返回一个非匿名的视图,要么返回一个动态对象来查看。
请参阅:http://rhizohm.net/irhetoric/post/2011/05/25/Taking-The-M-out-of-MVC-JSON-The-dynamic-Keyword-LINQ-.aspx
Unfortunately anonymous objects doesn't work with Views. Either you need to return a non-anonymous to view Or return a dynamic object to view.
Refer : http://rhizohm.net/irhetoric/post/2011/05/25/Taking-The-M-out-of-MVC-JSON-The-dynamic-Keyword-LINQ-.aspx
您不能在视图中使用匿名对象。尝试这样:
然后:
但我个人建议您使用强类型视图而不是 ViewBag:
并在视图内部:
You cannot use anonymous objects in views. Try like this:
and then:
But personally I would recommend you using strongly typed views instead of ViewBag:
and inside the view:
如果我将 linq 结果转换为控制器中的 toList() ,我就可以获取视图中的值。
var test = (从 db.EmpDetails 中的 p 按 p.EmpName 升序选择 p).ToList();
ViewBag.test = 测试;
谢谢....
I am able to get the values in the view if i convert linq result to toList() in controller.
var test = (from p in db.EmpDetails orderby p.EmpName ascending select p).ToList();
ViewBag.test = test;
Thanks....