2010-05-03 2 views
12

EF 모델의 사람들 이름과성에 레이블을 붙이고 싶습니다. 나는이 함께 시도했다 :SelectList 텍스트 설명에서 두 필드를 결합하는 방법은 무엇입니까?

public ActionResult Insert() 
     { 
      ViewData["accountlist"] = new SelectList(time.Anagrafica_Dipendente.ToList(), "ID_Dipendente", "Surname Name", null);    
      Giustificativi g = new Giustificativi(); 
      return View(g); 
     } 

을하지만, "성 이름"라는 속성이 없기 때문에 VS는 오류를 반환합니다. 어떻게 선택 목록 레이블에 이름과 성을 연결할 수 있습니까?

감사

답변

40

이 같은 것을 할 수있는 :

ViewData["accountlist"] = 
    new SelectList((from s in time.Anagrafica_Dipendente.ToList() select new { 
     ID_Dipendente=s.ID_Dipendente, 
     FullName = s.Surname + " " + s.Name}), 
     "ID_Dipendente", 
     "FullName", 
     null); 
+1

이 기술을 사용하면 다른 연결된 개체의 속성을 결합 할 수도 있습니다. 예 :'FullName = s.ParentSurname + s.Name' – Josh

26

time.Anagrafica_Dipendente에 새 속성을 추가 두 가지 속성의 연결 나타냅니다 :

public string Fullname 
{ 
    get 
    { 
     return string.Format("{0} {1}", Surname, Name); 
    } 
} 

을 다음 이것을 사용을 :

ViewData["accountlist"] = new SelectList(
    time.Anagrafica_Dipendente.ToList(), 
    "ID_Dipendente", 
    "Fullname", 
    null 
); 

업데이트 :

public string Fullname => string.Format("{0} {1}", Surname, Name); 

표현 바디 속성 here에 대해 자세히 알아 : C# 6.0으로,이 건물은 더 간결과 같이 쓸 수있다.

+1

작동하려면'Fullname'이'time.Anagrafica_Dipendente'의 멤버 여야합니다. –

+0

맞습니다. 나는 이것을 지정해야만했다. –

+0

나는 내 자아를 단순하고 우아하게 생각할 수 없다고 믿을 수 없다! – Ben

관련 문제