2012-06-06 8 views
0

보기의 개체 속성에 액세스합니다.MVC3 : ASP.NET MVC3 웹 응용 프로그램에서

나는 전망이있다. 뷰에는 IEnumerable 모델이 있습니다.

나는 모든 모델의 항목을 통해 루프 필요

에보기 item.Name을 보여 컨트롤러에서

@model IEnumerable<Object> 
@{ 
    ViewBag.Title = "Home"; 
} 

@foreach (var item in Model) 
{ 
    <div class="itemName">@item.Name</div> 
} 

, 나는 개체의 목록을 얻을 엔티티에 Linq에를 사용 데이터베이스에서.

감사관 :

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(); 
} 

내가이 오류를 얻을 실행

'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?) 

는 어떻게 모델 항목의 "이름"속성에 액세스 할 수 있습니까?

감사합니다 도움이

답변

3

메서드 반환을위한 강력한 형식을 만듭니다.

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; 
} 

... 그런

@model IQueryable<MyObject> 
0

내가 틀릴 수도 있지만 귀하의 모델 유형이 IEnumerable<Object>입니다 IEnumerable<dynamic> 대신

+1

... – jrummell

+0

에 나는 제대로 형식으로 코드를 얻을 수 없습니다. –

+0

은 작은 따옴표를 사용하고있었습니다. –

0

IEnumerable<Object>의 당신은 당신이 Person 속성에 액세스 할 수 있도록 IEnumerable<Person>로 변경, 사용하려고 수도에 대한 많은.

1

가장 쉬운 방법은 클래스 Person 정의하는 것, 그리고 작업 할 모델/컨트롤러를 변경 ... 새 모델을 반영하기 위해보기를 업데이트 개체 대신 IEnumerable<Person>

1

당신은 아마 명시 적 Casting

@(string) item.Name 

을하거나 dynamic 유형을 사용해야합니다. 뷰에서

변경

@model IEnumerable<Object> 

어떤 이해가되지 않습니다

@model IEnumerable<dynamic> 
관련 문제