[英]'object' does not contain a definition for 'type'
Im gettin this error but i dont know what it is. 我刚收到这个错误,但我不知道这是什么。 I've looked for the answer but none can answer main or maybe im just missing something. 我一直在寻找答案,但是没有人可以回答主要问题,或者我只是错过了一些东西。 Here my code: 这是我的代码:
Connection db = new Connection();
public ActionResult Index()
{
ViewBag.query = from input in db.field
where input.ID_FIELD == 1
select new {
type = input.FIELD_TYPE
};
return View();
}
and the view side 和视图方面
@foreach (var item in ViewBag.query)
{
@item.type//error here: 'object' does not contain a definition for 'type', why???
}
And if i make a simple select with where clause, work ok public ActionResult Index() { 并且,如果我使用where子句进行简单选择,则可以正常运行。公共ActionResult Index(){
ViewBag.query = from input in db.field
where input.ID_FIELD == 1
select input.FIELD_TYPE;
return View();
}
What could be my problem? 我可能是什么问题? I've seem many toturials doing the same and works great like this one i did just now: int[] number = { 1, 2, 3, 4, 5 }; 我似乎有许多toturial都在做同样的事情,并且像我刚才所做的那样工作得很好:int [] number = {1,2,3,4,5};
var query = from num in number
let x = num + num + num
select new {avg = x};
foreach (var item in query)
{
Console.WriteLine(item.avg);
}
Everything is ok here. 这里一切都很好。 Why could be the problem?? 为什么会出问题呢?
You can't return an anonymous type from a method. 您不能从方法中返回匿名类型。 Instead, create a new type and return that type. 而是,创建一个新类型并返回该类型。
For example: 例如:
ViewBag.query = from input in db.field
where input.ID_FIELD == 1
select new MyType() {
someField = input.FIELD_TYPE
};
public class MyType
{
public int someField {get;set;}//compatible with whatever type FIELD_TYPE is.
}
The problem is that ViewBag is dynamic
, but the anonymous object you're storing in it is not, so the compiler cannot access its properties directly. 问题在于ViewBag是dynamic
,但是您存储在其中的匿名对象不是动态的,因此编译器无法直接访问其属性。 You could just store a collection of values in the ViewBag property rather then the whole query: 您可以只在ViewBag属性中存储值的集合,而不是整个查询:
Connection db = new Connection();
public ActionResult Index()
{
ViewBag.types = from input in db.field
where input.ID_FIELD == 1
select input.FIELD_TYPE;
return View();
}
and then 接着
@foreach (var type in ViewBag.types)
{
@type
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.