2010-07-20 5 views
2

True/False 값을 sqlserver 비트 필드 (Featured)로 저장하는 테이블이 있습니다. 첫째, 수동으로 이외의 드롭 다운 목록을 생성하는 더 좋은 방법이 있습니까?MVC2의 단순 DropDownListFor?

둘째, 지금까지 내가 작동하지만 작동하지 않지만 DDL의 모든 항목에 selected="selected"을 추가하지 않았습니다.

편집 1 : 제안 나는 대답에 따라이 예제를 업데이 트했습니다 그리고 런타임 오류 :( 편집 2 결과 : 함수가 (와 캐스트없이) 작동처럼 사용 하지만 여전히 추가되지 않는 "선택"= 선택

모델 :.

// 
// View models 
public class SpotlightFormViewModel 
{ 

    // props 
    public Spotlight Spotlight { get; private set; } 
    public SelectList FeaturedMenu { get; private set; } 

    static IDictionary<string, int> feature = new Dictionary<string, int>(){ 
     {"True", 1}, 
     {"False", 0}, 
    }; 

    public IEnumerable<SelectListItem> FeaturedChoices(Spotlight spotlight) 
    { 
     return feature.Select(f => new SelectListItem 
     { 
      Text = f.Key, 
      Value = f.Value.ToString(), 
      Selected = spotlight.Featured, 
     }); 
    } 

    // constr 
    public SpotlightFormViewModel(Spotlight spotlight) 
    { 
     Spotlight = spotlight; 
     FeaturedMenu = new SelectList(FeaturedChoices(spotlight)); 
    } 
} 

컨트롤러 :

public ActionResult Edit(int id) 
    { 
     Spotlight spotlight = spotlightRepository.GetSpotlight(id); 

     return View(new SpotlightFormViewModel(spotlight)); 
    } 

보기 :

 <div class="editor-label"> 
      <%: Html.LabelFor(model => model.Spotlight.Featured) %> 
     </div> 
     <div class="editor-field"> 
      <%: Html.DropDownListFor(model => model.FeaturedMenu, Model.FeaturedChoices(Model.Spotlight))%> 
      <%: Html.ValidationMessageFor(model => model.Spotlight.Featured) %> 
     </div> 

답변

1

나는이 작업을 마침내 얻었다. 비록 내 문법 & 로직은 변수를 public IEnumerable FeaturedChoices(Spotlight spotlight)에 전달할 때 올바르지 만, 비록 내가 명시 적으로 Selected = true으로 표시된 경우에도 관계없이 작동하지 않습니다. 누군가가 대답 할 수 있다면 감사하겠다.

은 게터로 FeaturedChoices 속성을 만든 경우에만 적용됩니다.

보기 모델 아래의 전체 작업 코드 :

// 
// View models 
public class SpotlightFormViewModel 
{ 

    // props 
    public Spotlight Spotlight { get; private set; } 
    public SelectList FeaturedMenu { get; private set; } 

    static IDictionary<string, int> feature = new Dictionary<string, int>(){ 
     {"True", 1}, 
     {"False", 0}, 
    }; 

    public IEnumerable<SelectListItem> FeaturedChoices 
    { 
     get 
     {     
      return feature.Select(f => new SelectListItem 
      { 
       Text = f.Key, 
       Value = f.Value.ToString(), 
       Selected = IsSelected(this.Spotlight.Featured, f.Key) 
      }); 
     } 
    } 

    private bool IsSelected(bool featured, string val) 
    { 
     bool result = false; 

     if (String.Compare(val, "True") == 0 && featured) 
      result = true; 
     else if (String.Compare(val, "False") == 0 && !featured) 
      result = true; 

     return result; 
    } 

    // constr 
    public SpotlightFormViewModel(Spotlight spotlight) 
    { 
     Spotlight = spotlight; 
    } 
} 

컨트롤러 :

public ActionResult Edit(int id) 
    { 
     Spotlight spotlight = spotlightRepository.GetSpotlight(id); 

     return View(new SpotlightFormViewModel(spotlight)); 
    } 

보기 : 나는 N 무엇을 내 코드를 업데이 트했습니다

 <div class="editor-label"> 
      <%: Html.LabelFor(model => model.Spotlight.Featured) %> 
     </div> 
     <div class="editor-field"> 
      <%: Html.DropDownListFor(model => model.FeaturedMenu, Model.FeaturedChoices)%> 
      <%: Html.ValidationMessageFor(model => model.Spotlight.Featured) %> 
     </div> 
+0

당신이 그것을 알아 낸 것을 기쁘게 생각합니다 –

+0

도움을 주셔서 감사합니다 :). MVC를 사용하여 wysiwyg 편집기를 구현 한 블로그 수정 사항을 확인했습니다. 일단 내 viewmodels를 통과하면 CKEdit을 구현하려고합니다. 우리는 무슨 일이 일어날 지 알 것이다. – ryan

3

나는 당신이하는 것과 같은에서 dropdowlist를 사용합니다. 당신이 좋아하는 선택된 값을 추가 할 수 있습니다, 당신은 "선택"값에 대해 이야기 둘째

<%: Html.Label("True") %> 
<%: Html.RadioButtonFor(model => model.FeaturedMenu, "1") %> 

<%: Html.Label("False") %> 
<%: Html.RadioButtonFor(model => model.FeaturedMenu, "0") %> 

,하지만 당신은 "공공는 IEnumerable FeaturedChoices"그것을 사용하지 않은 :하지만 당신의 경우에 당신은 단순히 어떤 라디오 버튼을 사용할 수 있습니다 이 :

return feature.Select(f => new SelectListItem 
{ 
    Text = f.Key, 
    Value = f.Value.ToString(), 
    Selected = false 
}); 
+0

이 접근법을 가능케하는 일이 발생했다. 그러나 CS1928에서 'System.Web.Mvc.HtmlHelper '에 'DropDownListFor'에 대한 정의가없고 가장 좋은 확장 메서드 인 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor (System.Web.Mvc.HtmlHelper , System.Linq.Expressions.Expression >, System.Collections.Generic.IEnumerable ) '일부 잘못된 인수 ---- 을 가지고 <% : Html.DropDownListFor (...) %> – ryan

+0

어쩌면 문제는이 라인을 교체하여 문제를 해결할 수 있습니다 <% : Html.DropDownListFor (모델 => 모델. 특성 메뉴, 모델.FeaturedChoices) %> 의한 : <% : Html.DropDownListFor (모델 => model.FeaturedMenu (는 IEnumerable ) Model.FeaturedChoices) %> 은 알려주세요! –

+0

이것 좀더 살펴 줘서 고마워. CS0428 : 'FeaturedChoices'메서드 그룹을 'System.Collections.Generic.IEnumerable '대리자가 아닌 형식으로 변환 할 수 없습니다. 이 메소드를 호출하려고 했습니까? – ryan