2011-01-30 3 views
1

SelectList에서 선택한 ID (CountryId)의 텍스트 값 (CountryName)을 어떻게 표시합니까? SelectList는 Details 뷰 템플릿으로 전송 된 뷰 모델에 포함되어 있습니다. 필드에 현재 CountryID가 표시됩니다. 나는 CountryName을 원해.Asp mvc SelectList의 id 필드에서 텍스트 값 표시

보기

<div class="display-field">@Model.Dinner.CountryID</div> 

제어기

public class DinnerFormViewModel 
{ 
    public Dinner Dinner { get; private set; } 
    public SelectList CountriesList { get; private set; } 

    public DinnerFormViewModel(Dinner dinner) 
    { 
     Dinner = dinner; 

     var items = new List<Country>() { 
       new Country() { 
        CountryID = 1, 
        CountryName = "England" 
       }, 
       new Country() { 
        CountryID = 2, 
        CountryName = "Ireland" 
       }, 
       new Country() { 
        CountryID = 3, 
        CountryName = "Scotland" 
       }, 
       new Country() { 
        CountryID = 3, 
        CountryName = "Wales" 
       } 
      }; 

     CountriesList = new SelectList(items, "CountryID", "CountryName", 2); 
    } 
} 

가 다시 이것은 단지 라벨의 COUNTRYNAME 값을 표시하는

public ActionResult Details(int id) 
    { 
     Dinner dinner = dinnerRepository.GetDinner(id); 
     DinnerFormViewModel model = new DinnerFormViewModel(dinner); 
     if (dinner == null) 
      return View("NotFound");  
     else   
      return View("Details", model); 
    } 

뷰 모델. 그나 그 밖의 것을 편집하고 싶지 않다. LINQ 표현식?

답변

2

related 게시물에 대한 감사와

<div class="display-label">Country</div> 
<div class="display-field">@Html.Encode(Model.CountriesList.SingleOrDefault(c => int.Parse(c.Value) == Model.Dinner.CountryID).Text)</div> 

잘 작동합니다.

1

나는 조회를 돕기 위해 새로운 클래스를 만들 것이다. 내 예제 코드에서 클래스는 "BusinessResources"입니다.이 클래스에서는 아래에 국가별로 표시된 것과 같은 각 조회에 대한 메서드를 만듭니다. 사전은 당신이 성취하고자하는 것에 완벽합니다.

public static Dictionary<string, string> GetCountryList() 
     { 
      Dictionary<string, string> country = new Dictionary<string, string>(); 

      Capture2Entities db = new Capture2Entities(); 
      country = db.CountryLists.Where(x => x.IsDisabled == false) 
           .OrderBy(x => x.CountryName) 
           .Select(x => new { x.ID_Country, x.CountryName }) 
           .ToDictionary(key => key.ID_Country.ToString(), val => val.CountryName); 
      return country; 
     } 

보기이

<div class="display-label">@Html.LabelFor(model => model.ID_Country)</div> 
<div class="display-field">@Html.DropDownListFor(model => model.ID_Country, new SelectList(BusinessResources.GetCountryList(),"Key","Value"))</div> 
과 같을 것이다