2011-10-09 3 views
1

내가 데이터 주석을 사용한 클래스를 가지고 : 나는 또한 내가 이런 식으로 호출 할 수 있습니다 RadioButtonListFor라는 사용자 지정 Html 헬퍼를 만든맞춤 HtmlHelper에 유효성 검사 메시지를 어떻게 추가합니까?

[Required(ErrorMessage = "You must indicate which sex you are.)] 
public string Sex { get; set; } 

:

@Html.RadioButtonListFor(m => m.Sex, "SexList") 

내 SexList는 다음과 같이 정의된다 :

IList<string> SexList = new List() { "Male", "Female"}; 

그리고 아래 RadioButtonListFor 확장 (완전히 아직 완료되지 않음)된다

public static class RadioButtonListForExtentions 
{ 
    public static IHtmlString RadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string list) 
    { 
     string prefix = ExpressionHelper.GetExpressionText(expression); 
     if (string.IsNullOrEmpty(prefix)) 
      prefix = "empty"; 
     int index = 0; 

     var items = helper.ViewData.Eval(list) as IEnumerable; 
     if (items == null) 
      throw new NullReferenceException("Cannot find " + list + "in view data"); 

     string txt = string.Empty; 
     foreach (var item in items) 
     { 
      string id = string.Format("{0}_{1}", prefix, index++).Replace('.','_'); 
      TagBuilder tag = new TagBuilder("input"); 
      tag.MergeAttribute("type", "radio"); 
      tag.MergeAttribute("name", prefix); 
      tag.MergeAttribute("id", id); 
      tag.MergeAttribute("data-val-required", "Missing"); 
      tag.MergeAttribute("data-val", "true"); 

      txt += tag.ToString(TagRenderMode.Normal); 
      txt += item; 
     } 

     return helper.Raw(txt); 
    } 
} 

내 문제는 이것이다 : 지금 내가 속성에서 "없음"이라는 단어를 하드 코딩 한 "데이터 val- 필수 ". 어떻게 내 데이터 주석에 언급 된 텍스트를받을 수 있나요?

답변

1

아 ..., 솔루션 나 자신을 발견 유효성 검사 항목 사전. 그리고 이것들을 반복하면서 그것들을 추가하면 매력처럼 작동합니다!

2011 년 10 월 13 일 수정 :

아래의 해결책으로 마무리되었습니다. 문자열 목록을 얻는 대신 키가 라디오 버튼 값이고 사전 값이 라디오 버튼 텍스트 인 사전을 보내기로 결정했습니다.

public static IHtmlString RadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string list) 
    { 
     string prefix = ExpressionHelper.GetExpressionText(expression); 
     if (string.IsNullOrEmpty(prefix)) 
      prefix = "empty"; 

     // find existing value - if any 
     string value = helper.ViewData.Eval(prefix) as string; 

     var validationAttributes = helper.GetUnobtrusiveValidationAttributes(prefix); 
     string txt = string.Empty; 

     // create hidden field for error msg/value 
     TagBuilder tagHidden = new TagBuilder("input"); 
     tagHidden.MergeAttribute("type", "hidden"); 
     tagHidden.MergeAttribute("name", prefix); 
     tagHidden.MergeAttribute("value", value); 
     tagHidden.MergeAttribute("id", prefix.Replace('.', '_')); 
     foreach (KeyValuePair<string, object> pair in validationAttributes) 
     { 
      tagHidden.MergeAttribute(pair.Key, pair.Value.ToString()); 
     } 
     txt += tagHidden.ToString(TagRenderMode.Normal); 

     // prepare to loop through items 
     int index = 0; 
     var items = helper.ViewData.Eval(list) as IDictionary<string, string>; 
     if (items == null) 
      throw new NullReferenceException("Cannot find " + list + "in view data"); 

     // create a radiobutton for each item. "Items" is a dictionary where the key contains the radiobutton value and the value contains the Radiobutton text/label 
     foreach (var item in items) 
     { 
      string id = string.Format("{0}_{1}", prefix, index++).Replace('.','_'); 
      TagBuilder tag = new TagBuilder("input"); 
      tag.MergeAttribute("type", "radio"); 
      tag.MergeAttribute("name", prefix); 
      tag.MergeAttribute("id", id); 
      tag.MergeAttribute("value", item.Key); 
      if (item.Key == value) 
       tag.MergeAttribute("checked", "true"); 
      tag.MergeAttribute("onclick", "javascript:" + tagHidden.Attributes["id"] + ".value='" + item.Key + "'"); 
      txt += tag.ToString(TagRenderMode.Normal); 
      txt += item.Value; 
     } 

     return helper.Raw(txt); 
    } 
관련 문제