2016-12-10 4 views
0

핵심 MVC에는 태그 헬퍼라는 새로운 개념이 있습니다.TagHelpers는 유효성 검사 속성을 기반으로 LabelTagHelper에 대한 사용자 정의 클래스를 추가합니다. [필수]

이전에 [필수]와 같은 유효성 검사 데이터 주석을 기반으로 일부 클래스를 연결하기 위해 사용자 정의 HTML 도우미를 만들 수있었습니다. 나는 다음과 같은 달성하기 위해 자원 anough 찾을 수 없습니다 TagHelpers의 ARQ 아주 새로운 영역으로

:

[Required] 
    public Gender Gender { get; set; } 

보기 :

<label class="control-label col-md-3 required" asp-for="Gender"></label> 

CSS :

여기

뷰 모델입니다

.required:after { 
content: "*"; 
font-weight: bold; 
color: red; 
} 

출력 : enter image description here

하지만 레이블에 필요한 CSS 클래스를 추가하지 않으려합니다. 어떻게 든 모델 데이터 주석을 읽도록 LabelTagHelper를 확장 할 수 있어야하고 [Required]가있는 경우 레이블 요소에 필수 클래스를 추가해야합니다.

감사합니다,

답변

2

그래, 당신은 LabelTagHelper 클래스에서 상속 먼저 속성 목록에 자신의 클래스에 추가하여 아주 쉽게 확장 할 수 있습니다.

[HtmlTargetElement("label", Attributes = "asp-for")] 
public class RequiredLabelTagHelper : LabelTagHelper 
{ 
    public RequiredLabelTagHelper(IHtmlGenerator generator) : base(generator) 
    { 
    } 

    public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) 
    { 
     if (For.Metadata.IsRequired) 
     { 
      CreateOrMergeAttribute("class", "required", output); 
     } 

     return base.ProcessAsync(context, output); 
    } 

    private void CreateOrMergeAttribute(string name, object content, TagHelperOutput output) 
    { 
     var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == name); 
     if (currentAttribute == null) 
     { 
      var attribute = new TagHelperAttribute(name, content); 
      output.Attributes.Add(attribute); 
     } 
     else 
     { 
      var newAttribute = new TagHelperAttribute(
       name, 
       $"{currentAttribute.Value.ToString()} {content.ToString()}", 
       currentAttribute.ValueStyle); 
      output.Attributes.Remove(currentAttribute); 
      output.Attributes.Add(newAttribute); 
     } 
    } 
} 
+0

나는 곧 답변을 수락 할 것이다. 그것이 효과가있는 것처럼 보입니다. 감사합니다 – akd

+0

이것은 완벽하게 작동합니다. 커스텀 태그 도우미가 생성되면 _ViewImports.cshtml 파일에서 참조 되어야만 작동한다는 것을 언급 할 필요가 있습니다. @addTagHelper "*, WebApplicaiton.Web" – akd

+1

이건 약간 오래된 것 같아.하지만 var attribute = new TagHelperAttribute ("class", content);'var attribute = new TagHelperAttribute (name , content);'이것은 속성 이름에 의존하지 않으므로 코딩 된'class' 이름은 나에게 틀린 것 같습니다. 그렇지 않으면 나를 +1합니다. – Nico