in an ASP.NET MVC3 web application.
I have a view. the view has a IEnumerable model.
I need to loop through all the model's items and show the item.Name
The view:
@model IEnumerable<Object>
@{
ViewBag.Title = "Home";
}
@foreach (var item in Model)
{
<div class="itemName">@item.Name</div>
}
In the controller, I use Linq to entities to get the list of objects from the database.
The Controller:
public ActionResult Index()
{
IEnumerable<Object> AllPersons = GetAllPersons();
return View(AllSurveys);
}
public IEnumerable<Object> GetAllPersons()
{
var Context = new DataModel.PrototypeDBEntities();
var query = from p in Context.Persons
select new
{
id = p.PersonsId,
Name = p.Name,
CreatedDate = p.CreatedDate
};
return query.ToList();
}
When I run I get this error:
'object' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
How can I access the "Name" Property of the model items?
Thanks a lot for any help
Create a strong type for your method return.
public class MyObject {
public int id {get;set;}
public string Name {get;set;}
public DateTime CreatedDate {get;set;}
}
public IQueryable<MyObject> GetAllPersons()
{
var Context = new DataModel.PrototypeDBEntities();
var query = from p in Context.Persons
select new MyObject
{
id = p.PersonsId,
Name = p.Name,
CreatedDate = p.CreatedDate
};
return query;
}
... Then update your view to reflect the new model ...
@model IQueryable<MyObject>
最简单的方法是定义一个Person
类,并更改模型/控制器以使用IEnumerable<Person>
而不是object。
You probably need to do an explicit Casting
@(string) item.Name
or use dynamic
type.
In the view, Change
@model IEnumerable<Object>
to
@model IEnumerable<dynamic>
我可能是错的,但您可能尝试使用IEnumerable<dynamic>
而不是IEnumerable<Object>
您的模型类型为IEnumerable<Object>
,将其更改为IEnumerable<Person>
以便您可以访问Person
属性。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.