0

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

0

5 Answers 5

3

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> 
Sign up to request clarification or add additional context in comments.

Comments

1

The easiest way would be to define a class Person, and to change your model/controller to work with IEnumerable<Person> instead of object.

Comments

1

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> 

Comments

0

Your model type is IEnumerable<Object>, change it to IEnumerable<Person> so that you can access Person properties.

Comments

0

I could be wrong but you might try to use IEnumerable<dynamic> instead of IEnumerable<Object>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.