Home > Software engineering >  Extension Method for Default HtmlHelper in RazorPage (ASP NET CORE)
Extension Method for Default HtmlHelper in RazorPage (ASP NET CORE)

Time:09-30

Is it possible to use extension method for TextboxFor,DropdownlistFor etc in NET Core 6?

Most of the example i've seen only had the solution for NET MVC. Since net mvc use System.Web.MVC instead of Microsoft.AspNetCore.Mvc, i have no idea on how to implement it.

This is the extension method:

public static class InputDisabler
{
    public static HtmlString DisableInput(this IHtmlHelper htmlString, Func<bool> expression)
    {
        if (expression.Invoke())
        {
            string formattedHtml = htmlString.ToString();
            int index = formattedHtml.IndexOf('>');

            formattedHtml = formattedHtml.Insert(index, " disabled=\"disabled\"");
            return new HtmlString(formattedHtml);
        }
        return new HtmlString(htmlString.ToString());
    }
}

But this extension applied as a custom helper instead of extension of default ones.

What i want: @Html.DropdownListFor(x => x.ListData).DisableInput(() => Model.CurrentUser != Model.CreatedBy)

Is there anyway on how to solve this? I'm still learning about these things in C# so any advice is helpful.

CodePudding user response:

Try to change this IHtmlHelper to this IHtmlContent in your extension method:

public static class InputDisabler
{
    public static HtmlString DisableInput(this IHtmlContent htmlString, Func<bool> expression)
    {
        if (expression.Invoke())
        {
            string formattedHtml = htmlString.ToString();
            int index = formattedHtml.IndexOf('>');

            formattedHtml = formattedHtml.Insert(index, " disabled=\"disabled\"");
            return new HtmlString(formattedHtml);
        }
        return new HtmlString(htmlString.ToString());
    }
}

DropdownListFor returns IHtmlContent so you need to do this to be able to chain them.

  • Related