3

나는 기본 내 선택 목록의 값을 설정하려면이 코드가 있습니다설정 기본값은 편집기 템플릿 내부 selectList의 값을 선택

public ActionResult Register() 
{ 
    IList<Country> countryList = _countryRepository.GetAllCountry(); 

    var registerViewModel = new RegisterViewModel 
    { 
     CountryId = 52, 
     CountryList = new SelectList(countryList, "CountryId", "CountryName", "Select Country") 
    }; 

    return View(registerViewModel); 
} 

내가보기에이 있고이 잘 작동에 선택한 국가 값을 설정을 52 : 나는이에 대한 편집기 템플릿을 만들 때

<%: Html.DropDownListFor(model => model.CountryId, Model.CountryList ,"Select Country") %> 

는하지만, 국가의 기본 값은 그래서, 나는이 내 현재보기를 변경

을 선택하지 않은 :

<%: Html.EditorFor(model => model.CountryId,new { countries = Model.CountryList}) %> 

가 그럼 난 이렇게 내 편집기 템플릿을 생성 :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Int64?>" %> 
<%= Html.DropDownList(
     String.Empty /* */, 
     (SelectList)ViewData["countries"], 
     "Select Country" 
    ) 
%> 

답변

7

내가 내 컨트롤러에 코드를 대체하여이 문제를 해결 한 :

CountryList = new SelectList(countryList, "CountryId", "CountryName",52 /*Default Country Id*/) 

당신은 더 나은 솔루션을 가지고, 제발 저에게 알려주세요. 나는 받아 들인 대답을 바꿀 것이다.

1

당신의 컨트롤러에이 추가 :

ViewData["CountryList"] = new SelectList(_countryRepository.GetAllCountry(), 52); 

을 그리고,보기 페이지에서 호출 드롭 다운을 다음과 같이

@Html.DropDownList("Countries", ViewData["CountryList"] as SelectList)