2010-04-14 1 views
0

내 드롭 다운 목록에서 여러 개의 드롭 다운 목록에 사용할 내 모델의 옵션 목록 (IEnumerable < SelectListItem>)이 있습니다. 그러나 이러한 각 드롭 다운에는 다른 옵션이있을 수 있습니다.ASP.NET MVC의 드롭 다운 목록에 선택한 옵션을 지정하는 가장 쉬운 방법

Html.DropDownList 도우미를 사용하는 경우 specfiy를 선택하는 쉬운 방법이 있습니까? 이 시점에서

는, 내가 볼 수있는 유일한 방법은 지금과 같은 옵션 목록을 통해 HTML에게 자신과 루프를 생성하는 것입니다 :

<% for(int i=0; i<10; i++) { %> 
    <select name="myDropDown<%= i %>"> 
     <% foreach(var option in Model.Options) { %> 
     <option value="<%= Html.Encode(option.optValue) %>" <%if(ShouldBeSelected(i)) {%> selected="selected"<% } %>><%= Html.Encode(option.optText) %></option> 
     <% } %> 
    </select> 
<% } %> 

답변

3

Html.DropDownList()가 매개 변수로 selectList의를 수용 SelectedValue 속성 SelectList를 만들 때 SelectItem을 지정하고 SelectList를 Html.DropDownList()에 전달합니다.

-1

다음은 페이지에 7 개의 드롭 다운이 있으며 각각 5 개의 동일한 옵션이있는 예입니다. 드롭 다운마다 다른 옵션을 선택할 수 있습니다. 컨트롤러 방식에서 이제

public class HomePageViewModel 
{ 
    public List<SelectListItem> AllItems { get; set; } 

    public string ValueForList1 { get; set; } 
    public string ValueForList2 { get; set; } 
    public string ValueForList3 { get; set; } 
    public string ValueForList4 { get; set; } 
    public string ValueForList5 { get; set; } 
    public string ValueForList6 { get; set; } 
    public string ValueForList7 { get; set; } 

    public HomePageViewModel() 
    { 
     AllItems = new List<SelectListItem> 
     { 
      new SelectListItem {Text = "First", Value = "First"}, 
      new SelectListItem {Text = "Second", Value = "Second"}, 
      new SelectListItem {Text = "Third", Value = "Third"}, 
      new SelectListItem {Text = "Fourth", Value = "Fourth"}, 
      new SelectListItem {Text = "Fifth", Value = "Fifth"}, 
     }; 
    } 
} 

는 다음과 같이 선언 :이 같은 뷰 모델이 다음

<%= Html.DropDownListFor(m => m.ValueForList1, Model.AllItems)%> 
<%= Html.DropDownListFor(m => m.ValueForList2, Model.AllItems)%> 
<%= Html.DropDownListFor(m => m.ValueForList3, Model.AllItems)%> 
<%= Html.DropDownListFor(m => m.ValueForList4, Model.AllItems)%> 
<%= Html.DropDownListFor(m => m.ValueForList5, Model.AllItems)%> 
<%= Html.DropDownListFor(m => m.ValueForList6, Model.AllItems)%> 
<%= Html.DropDownListFor(m => m.ValueForList7, Model.AllItems)%> 

: 내보기에서

, 나는 내 양식 안에 다음 코드를

 public ActionResult Submit(HomePageViewModel viewModel) 

viewModel.ValueForList1의 값은 선택한 값으로 설정됩니다.

물론 데이터베이스에서 어떤 종류의 enum 또는 id를 사용하는 것이 좋습니다. 속성 '아이디'와 '이름'
뷰 모델 클래스는 속성 'SelectedItemId'
항목이 = IEnumerable을 < 항목에

1

클래스 '항목'>

<%=Html.DropDownList("selectname", items.Select(i => new SelectListItem{ Text = i.Name, Value = i.Id.ToString(), Selected = Model.SelectedItemId.HasValue ? i.Id == Model.SelectedItemId.Value : false })) %> 
관련 문제