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.d开发者_JAVA百科eptName
};
ViewBag.test = test1;
and in the view
@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'".
Please help me to solve this error. Thanks san
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
You cannot use anonymous objects in views. Try like this:
var test1 =
from ed in db.EmpDetails
join dp in db.Departments on ed.EmpDept equals dp.DeptId
select ed;
ViewBag.test = test1;
and then:
@foreach (var tm in (IEnumerable<Employee>)ViewBag.test)
{
string abc = tm.EmpName;
// and the logic
}
But personally I would recommend you using strongly typed views instead of ViewBag:
var test1 =
from ed in db.EmpDetails
join dp in db.Departments on ed.EmpDept equals dp.DeptId
select ed;
return View(test1);
and inside the view:
@model IEnumerable<Employee>
@foreach (var tm in Model)
{
string abc = tm.EmpName;
// and the logic
}
I am able to get the values in the view if i convert linq result to toList() in controller.
Like
var test = (from p in db.EmpDetails orderby p.EmpName ascending select p).ToList(); ViewBag.test = test;
And in the view
@foreach (var tm in ViewBag.test)
{
int emId = @tm.id;
}
Thanks....
精彩评论