نوشتن TagHelperهای سفارشی برای ASP.NET Core
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۷/۰۷ ۱۴:۲۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
<ul class="list-group"> <li class="list-group-item">Item 1</li> <li class="list-group-item">Item 2</li> <li class="list-group-item">Item 3</li> </ul>
{
"version": "1.0.0-*",
"dependencies": {
"NETStandard.Library": "1.6.0",
"Microsoft.AspNetCore.Http.Extensions": "1.0.0",
"Microsoft.AspNetCore.Mvc.Abstractions": "1.0.1",
"Microsoft.AspNetCore.Mvc.Core": "1.0.1",
"Microsoft.AspNetCore.Mvc.ViewFeatures": "1.0.1",
"Microsoft.AspNetCore.Razor.Runtime": "1.0.0"
},
"frameworks": {
"netstandard1.6": {
"imports": "dnxcore50"
}
}
} namespace Core1RtmEmptyTest.TagHelpers
{
[HtmlTargetElement("list-group")]
public class ListGroupTagHelper : TagHelper
{
[HtmlAttributeName("asp-items")]
public List<string> Items { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
}
}
} <list-group></list-group>
<list-group asp-items="Model.Items"></list-group>
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Core1RtmEmptyTest.TagHelpers
{
[HtmlTargetElement("list-group")]
public class ListGroupTagHelper : TagHelper
{
[HtmlAttributeName("asp-items")]
public List<string> Items { get; set; }
protected HttpRequest Request => ViewContext.HttpContext.Request;
[ViewContext, HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
if (Items == null)
{
throw new InvalidOperationException($"{nameof(Items)} must be provided");
}
output.TagName = "ul";
output.TagMode = TagMode.StartTagAndEndTag;
output.Attributes.Add("class", "list-group");
foreach (var item in Items)
{
TagBuilder itemBuilder = new TagBuilder("li");
itemBuilder.AddCssClass("list-group-item");
itemBuilder.InnerHtml.Append(item);
output.Content.AppendHtml(itemBuilder);
}
}
}
} @addTagHelper *,Core1RtmEmptyTest.TagHelpers
using System.IO;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Html;
namespace Sample
{
/// <summary>
/// Html Helper Extensions
/// </summary>
public static class HtmlHelperExtensions
{
/// <summary>
/// Convert IHtmlContent/TagBuilder to string
/// </summary>
public static string GetString(this IHtmlContent content)
{
using (var writer = new StringWriter())
{
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
}
} var tagHelper = new MyCustomTagHelper();
var tagHelperContext = new TagHelperContext(
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: Guid.NewGuid().ToString("N"));
var tagHelperOutput = new TagHelperOutput(
tagName: "div",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent(string.Empty);
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
tagHelper.Process(tagHelperContext, tagHelperOutput);
var content = tagHelperOutput.Content.GetContent(); @addTagHelper *, core-resources
"buildOptions": {
"outputName": "core_resources"
}, @addTagHelper *, core_resources
Menu.ChildsList.Add(new ChildMenu()
{
Text = "داشبورد",
Url = url.Action(new UrlActionContext() { Action = "Index", Controller = "Home"})
}); var urlHelper = ViewContext.HttpContext.Items.Values.OfType<IUrlHelper>().FirstOrDefault();
// How to inject the ViewContext automatically
[ViewContext, HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
// How to use the injected ViewContext
IUrlHelper urlHelper = new UrlHelper(ViewContext);
var actionUrl = urlHelper.Action(action: nameof(MyController.Xyz),
controller: nameof(MyController).Replace("Controller", string.Empty),
values:
new
{
//...,
area = "SomeName"
}); IUrlHelper urlHelper = new UrlHelper(_actionContextAccessor.ActionContext);
adminMenu.ChildsList.Add(new ChildMenu()
{
Text = "مدیریت کاربران",
Url = urlHelper.Action("Index","UserManager",values:new{area:"Identity"})
});
//MyHelpers.cshtml:
//Recursive function for rendering child nodes for the specified node
@helper CreateNavigation(int parentId, int depthNavigation, int currentPageId)
{
@MyHelpers.Navigation(parentId, depthNavigation, currentPageId);
}
@helper Navigation(int parentId, int depthNavigation, int currentPageId)
{
if ()
{
if ()
{
<ul style="">
@foreach ()
{
if ()
{
<li class="">
@Navigation(child.Id, depthNavigation, currentPageId)
</li>
}
}
</ul>
}
}
} //I call the method in _Menu.cshtml: @MyHelpers.CreateNavigation(rootNode.Id, 2,currentPageId);
@addTagHelper *,KanalexUI.Classes.TagHelpers
@addTagHelper *, KanalexUI
[HtmlTargetElement("img-gravatar")]
public class GravatarTagHelper : TagHelper
{
[HtmlAttributeName("email")]
public string Email { get; set; }
[HtmlAttributeName("alt")]
public string Alt { get; set; }
[HtmlAttributeName("class")]
public string Class { get; set; }
[HtmlAttributeName("size")]
public int Size { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!string.IsNullOrWhiteSpace(Email))
{
var hash = Md5HashHelper.GetHash(Email);
output.TagName = "img";
if (!string.IsNullOrWhiteSpace(Class))
{
output.Attributes.Add("class", Class);
}
if (!string.IsNullOrWhiteSpace(Alt))
{
output.Attributes.Add("alt", Alt);
}
output.Attributes.Add("src", GetAvatarUrl(hash, Size));
output.TagMode = TagMode.SelfClosing;
}
}
private static string GetAvatarUrl(string hash, int size)
{
var sizeArg = size > 0 ? $"?s={size}" : "";
return $"https://www.gravatar.com/avatar/{hash}{sizeArg}";
} <img-gravatar email="@Model.Email" class="img-thumbnail" size="150" />