همه ما با DisplayAttribute در DataAnnotaion آشنا هستیم. چیزی شبیه زیر برای یک موجودیت:
public class Student{ [Display(Name="نام خانوادگی")] public string FamilyName { get; set;} }
با استفاده از tag helper ای به نام asp-for میتوان متادیتای Name را به کاربر، در سمت رابط کاربری نشان داد؛ برای مثال:
<label asp-for="FamilyName"></label>
و یا موقع اعتبارسنجی میتوان به جای نشان دادن نام FamilyName از نام مفهومتری مانند نام خانوادگی استفاده نمود.
چه خوب بود اگر میشد علاوه بر نام، توصیفی از فیلد نیز برای آن در این قسمت وجود داشته باشد؛ به عبارت دیگر اگر کد زیر را داشتیم:
[Display( Name = "نام خانوادگی", Description = "بهتر است فقط در اینجا نام خانوادگی شخص وارد شود")] public string FamilyName{ get; set; }
بتوان از tag helper ای مانند زیر استفاده نمود:
<span asp-description-for="FamilyName"></span>
که در نهایت چنین خروجی html ای داشته باشیم:
<span>بهتر است فقط در اینجا نام خانوادگی شخص وارد شود</span>
برای این منظور میتوان از کلاس زیر بهره برد:
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; [HtmlTargetElement("div", Attributes = ForAttributeName)] [HtmlTargetElement("p", Attributes = ForAttributeName)] [HtmlTargetElement("span", Attributes = ForAttributeName)] public sealed class DescriptionForTagHelper : TagHelper { private const string ForAttributeName = "asp-description-for"; [HtmlAttributeName(ForAttributeName)] public ModelExpression For { get; set; } = default!; public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } var description = For.Metadata.Description; if (description != null) { // Do not update the content if another tag helper // targeting this element has already done so. if (!output.IsContentModified) { var childContent = await output.GetChildContentAsync(); if (childContent.IsEmptyOrWhiteSpace) { output.Content.SetHtmlContent(description); } else { output.Content.SetHtmlContent(childContent); } } } } }
کلاس DescriptionForTagHelper از کلاس پایه TagHelper ارث بری نموده است و متد ProcessAsync آن به نحوی که asp-description-for را بپذیرد override شده است.
حوزه اعمال این tag helper به span، p و div محدود شده است؛ اما میتوان با گذاشتن یک ستاره (*) آن را به کل المانهای html اعمال کرد.