ASP.NET Core Partial View ve View Component İçerisinde Section Tanımlayabilmek

A

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.

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();
        }
    }
}

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.

C# – ASP.Net Core MVC
<scripts render="true"></scripts>

Partial View ve View Component View leriniz içerisinde aşağıdaki kodlarınızı aşağıdaki gibi kullanabilirsiniz.

C# – ASP.NET Core MVC
<scripts>
  <script>
  // JavaScript, jQuery kodlarınızı buraya yazabilirsiniz.
  </script>
</scripts>

Yorum yazın

By Sinan BOZKUŞ

Sinan BOZKUŞ

Get in touch

Quickly communicate covalent niche markets for maintainable sources. Collaboratively harness resource sucking experiences whereas cost effective meta-services.