Skip to content

Instantly share code, notes, and snippets.

@A-Programmer
Last active May 6, 2018 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A-Programmer/a37833e2c466eeef3657fe1b12af6d35 to your computer and use it in GitHub Desktop.
Save A-Programmer/a37833e2c466eeef3657fe1b12af6d35 to your computer and use it in GitHub Desktop.
ساخت TagHelper اختصاصی در ASP.NET Core

آموزش ساخت TagHelper اختصاصی در DotNet Core:

اگر در مورد تگ هلپرها نمی دانید، می توانید به صفحه اینستاگرام یا كانال تلگرامی كه در انتهای مقاله نوشته شده است مراجعه كنید.

در این مقاله می خواهیم یك تگ هلپر برای پراگرس بار بوت استرپ بنویسیم. با توجه به مستندات بوت استرپ كد زیر یك پراگرس بار ساده را برای ما نمایش می دهد:

'

60% Complete

در این مثال قصد داریم یك تگ div بنویسیم كه ورودی هایی مثل كمترین، بیشترین و مقدار فعلی را به صورت خصوصیت به آن ارسال كنیم كه در نهایت زمان نمایش همان كدهای مربوط به پراگرس بار یا نوار پیشرفت برای ما تولید شود.

 ks-progress-max="100" 
 ks-progress-min="0">

تگ هلپر كلاس ساده ای است كه از كلاس پایه TagHelper ارث بری می كند. ابتدا باید خصوصیت المنت هدف را مشخص كنیم، در مثال ما قرار است هر تگ div ای كه خصوصیت ks-progress-value دارد هدف ما باشد. یک پوشه می سازیم و درون این پوشه کلاسی به صورت زیر درست میکنیم:

[HtmlTargetElement("div", Attributes = ProgressValueAttributeName)] public class ProgressBarTagHelper : TagHelper { private const string ProgressValueAttributeName = "ks-progress-value";
//.... }

در خط اول خصوصیاتی که اجباری هستند را اضافه میکنیم.در این مثال خصوصیات ks-progress-max و ks-progress-min به صورت اجباری تعریف نکردیم. بجای اجباری تعریف کردن این دو خصوصیت به صورت پیش فرض مقدار 0 و 100 را در نظر می گیریم. کلاس را به صورت زیر تغییر می دهیم:

[HtmlTargetElement("div", Attributes = ProgressValueAttributeName)] public class ProgressBarTagHelper : TagHelper { private const string ProgressValueAttributeName = "ks-progress-value"; private const string ProgressMinAttributeName = "ks-progress-min"; private const string ProgressMaxAttributeName = "ks-progress-max";

[HtmlAttributeName(ProgressValueAttributeName)]
public int ProgressValue { get; set; }

[HtmlAttributeName(ProgressMinAttributeName)]
public int ProgressMin { get; set; } = 0;

[HtmlAttributeName(ProgressMaxAttributeName)]
public int ProgressMax { get; set; } = 100;

//...

}

در نهایت باید متد Process یا ProcessAsync را آورراید کنیم.در این مثال منطق ما ساده می باشد و نیازی به انجام Async کارها نداریم. کلاس ما به صورت زیر خواهد بود :

[HtmlTargetElement("div", Attributes = ProgressValueAttributeName)] public class ProgressBarTagHelper : TagHelper { private const string ProgressValueAttributeName = "ks-progress-value"; private const string ProgressMinAttributeName = "ks-progress-min"; private const string ProgressMaxAttributeName = "ks-progress-max";

/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName(ProgressValueAttributeName)]
public int ProgressValue { get; set; }

[HtmlAttributeName(ProgressMinAttributeName)]
public int ProgressMin { get; set; } = 0;

[HtmlAttributeName(ProgressMaxAttributeName)]
public int ProgressMax { get; set; } = 100;

public override void Process(TagHelperContext context, TagHelperOutput output)
{
    var progressTotal = ProgressMax - ProgressMin;

    var progressPercentage = Math.Round(((decimal) (ProgressValue - ProgressMin) / (decimal) progressTotal) * 100, 4);

    string progressBarContent =             

$@"

{progressPercentage}% Complete

"; output.Content.AppendHtml(progressBarContent);
    string classValue;
    if (output.Attributes.ContainsName("class"))
    {
        classValue = string.Format("{0} {1}", output.Attributes["class"].Value, "progress");
    }
    else
    {
        classValue = "progress";
    }

    output.Attributes.SetAttribute("class", classValue);
}

}

در نهایت کدهایی اضافه میکنیم که چک کند مقادیر Min,Max و Value مناسب باشند.به عنوان مثال مقدار Min باید کمتر از Max باشد. پیاده سازی نهایی کلاس به صورت زیر خواهد بود:

[HtmlTargetElement("div", Attributes = ProgressValueAttributeName)] public class ProgressBarTagHelper : TagHelper { private const string ProgressValueAttributeName = "ks-progress-value"; private const string ProgressMinAttributeName = "ks-progress-min"; private const string ProgressMaxAttributeName = "ks-progress-max";

/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName(ProgressValueAttributeName)]
public int ProgressValue { get; set; }

[HtmlAttributeName(ProgressMinAttributeName)]
public int ProgressMin { get; set; } = 0;

[HtmlAttributeName(ProgressMaxAttributeName)]
public int ProgressMax { get; set; } = 100;

public override void Process(TagHelperContext context, TagHelperOutput output)
{
    if (ProgressMin >= ProgressMax)
    {
        throw new ArgumentException(string.Format("{0} باید کمتر از {1} باشد", ProgressMinAttributeName, ProgressMaxAttributeName));
    }

    if (ProgressValue > ProgressMax || ProgressValue < ProgressMin)
    {
        throw new ArgumentOutOfRangeException(string.Format("{0} باید بین {1} و {2} باشد", ProgressValueAttributeName, ProgressMinAttributeName, ProgressMaxAttributeName));
    }
    var progressTotal = ProgressMax - ProgressMin;

    var progressPercentage = Math.Round(((decimal) (ProgressValue - ProgressMin) / (decimal) progressTotal) * 100, 4);

    string progressBarContent =             

$@"

{progressPercentage}% Complete

"; output.Content.AppendHtml(progressBarContent);
    string classValue;
    if (output.Attributes.ContainsName("class"))
    {
        classValue = string.Format("{0} {1}", output.Attributes["class"].Value, "progress");
    }
    else
    {
        classValue = "progress";
    }

    output.Attributes.SetAttribute("class", classValue);

    base.Process(context, output);
}

}

کار ما با کلاس تگ هلپر اختصاصی تمام شد ولی برای اینکه بتوانیم از این تگ هلپر در پروژه استفاده کنیم ابتدا باید یک رفرنس به تگ هلپر ها بدهیم.برای ابن کار از دستور @addTagHelper استفاده می کنیم. در پوشه Views به دنبال فایل _ViewImports.cshtml بگردید و کدهای زیر را به آن اضافه کنید :

@addTagHelper ", Microsoft.AspNet.Mvc.TagHelpers" @addTagHelper ", CustomTagHelper"

در اینجا خط دوم CustomTagHelper نام پروژه ما است که شما باید نام پروژه خود را بنویسید. حالا در هر ویو می توانیم از این تگ هلپری که ساختیم استفاده کنیم :

در خط بالا مقادیر کمترین و بیشترین را وارد نکردیم تا از مقادیر پیش فرض استفاده شود ولی می توانم به صورت زیر این مقادیر را نیز اضافه کنیم :

موفق و پیروز باشید.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment