Partial View ve View Componentlerde mevcut yapıda Section kullanamamaktayız. Bu da Partial View veya View Componentlerimizde yazdığımız bazı Javascript / Jquery kodlarımızın Layout sayfasında alt kısımda çalıştırmak istediğimizde bize engel oluyor. Aşağıdaki bir taghelper yazarak bu soruna çözüm üretebilirsiniz.
[csharp]
public class ScriptsTagHelper : TagHelper
{
private static readonly object Itemskey = new Object();
private IDictionary<object, object> Items => _httpContextAccessor?.HttpContext?.Items;
private readonly IHttpContextAccessor _httpContextAccessor;
public ScriptsTagHelper(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
context.AllAttributes.TryGetAttribute("render", out var attribute);
var render = false;
if (attribute != null)
{
render = Convert.ToBoolean(attribute.Value.ToString());
}
if (render && Items.ContainsKey(Itemskey))
{
var scripts = (List<HtmlString>)Items[Itemskey];
var outputContent = String.Concat(scripts);
output.Content.SetHtmlContent(outputContent);
}
else
{
List<HtmlString> list;
if (!Items.ContainsKey(Itemskey))
{
list = new List<HtmlString>();
Items[Itemskey] = list;
}
list = (List<HtmlString>)Items[Itemskey];
var outputContent = await output.GetChildContentAsync();
list.Add(new HtmlString(outputContent.GetContent()));
output.Content.Clear();
}
}
}
[/csharp]
Scripts adlı bir tag helper oluşturduğumuzdan sayfa içerisinde tag helperımızı “<scripts>” olarak kullanacağız.
Aşağıdaki kodu javascript kodlarınızın layout sayfanızın neresinde çalışmasını istiyorsanız oraya yerleştirebilirsiniz.
[csharp]
<scripts render="true"></scripts>
[/csharp]
Partial View ve View Component View leriniz içerisinde aşağıdaki kodlarınızı aşağıdaki gibi kullanabilirsiniz.
[csharp]
<scripts>
<script>
// javascript, jquery kodlarınızı buraya yazabilirsiniz.
</script>
</scripts>
[/csharp]