0

I am rather new to Razor development. I want to set the disabled status of an input field based on a condition. So far, I have implemented the following:

<input type="text" class="form-control text-uppercase"
    asp-for="CustInfo.ORG_ID" 
    disabled="@(Model.RecMode == (short)RecModeId.Update ? "disabled" : null)" />

I want to improve the above implementation by doing something like the article:

https://www.codeproject.com/Tips/670129/Enable-Disable-controls-on-a-web-page-using-MVC-Ra

I have:

namespace Demo.AppExtensions
{
    public static class DisableHtmlControlExtension
    {
        public static IHtmlContent DisableIf(this HtmlString htmlString, Func<bool> expression)
        {
            if (expression.Invoke())
            {
                var html = htmlString.ToString();
                const string disabled = "\"disabled\"";
                html = html.Insert(html.IndexOf(">",
                  StringComparison.Ordinal), " disabled= " + disabled);
                return new HtmlString(html);
            }

            return htmlString;
        }
    }
}

When I tried to use it in a razor page, I have this error:

enter image description here

It seems like I didn't reference to the extension correctly. Any advice?

Dave B
  • 1,105
  • 11
  • 17
Ryan Ong
  • 3
  • 3

1 Answers1

1

The definition for Html.TextBoxFor in ASP.NET 7 returns Microsoft.AspNetCore.Html.IHtmlContent instead of MvcHtmlString that's listed in the article in your post.

Updating the DisableIf extension method from this HtmlString htmlString to this IHtmlContent htmlContent is the first fix.

The second is changing var html = htmlString.ToString(); to using htmlContent.WriteTo().

After these changes the extension method works.

namespace Demo.AppExtensions
{
    public static class DisableHtmlControlExtension
    {
        public static IHtmlContent DisableIf(
            //this HtmlString htmlString, Func<bool> expression)
            this IHtmlContent htmlContent, Func<bool> expression)
        {
            if (expression.Invoke())
            {
                // var html = htmlString.ToString();
                // https://stackoverflow.com/a/65155001
                StringWriter writer = new System.IO.StringWriter();
                htmlContent.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default);
                string html = writer.ToString();

                const string disabled = "\"disabled\"";
                html = html.Insert(html.IndexOf(">",
                  StringComparison.Ordinal), " disabled= " + disabled);
                return new HtmlString(html);
            }

            return htmlContent;
        }
    }
}

The extension method in use:

@Html.TextBoxFor(m=>m.CustInfo.ORG_ID, new { @class = "form-control text-uppercase" }).DisableIf(()=> Model.RecMode==(short)RecModeId.Update)
Dave B
  • 1,105
  • 11
  • 17