Search code examples
c#html-helperasp.net-coreasp.net-core-mvc

What is the equivalent of System.Web.Mvc.Html.InputExtensions in ASP.NET 5?


What is the ASP.NET 5 equivalent of System.Web.Mvc.Html.InputExtensions as used in ASP.NET 4?

See example below:

public static class CustomHelpers
{
    // Submit Button Helper
    public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText)
    {
        string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
        return new MvcHtmlString(str);
    }

    // Readonly Strongly-Typed TextBox Helper
    public static MvcHtmlString TextBoxFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, bool isReadonly)
    {
        MvcHtmlString html = default(MvcHtmlString);

        if (isReadonly)
        {
            html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
                expression, new { @class = "readOnly",
                @readonly = "read-only" });
        }
        else
        {
            html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression);
        }
        return html;
    }
}

Solution

  • For the ASP.NET 4 code:

        MvcHtmlString html = 
            System.Web.Mvc.Html.InputExtensions.TextBoxFor(
                htmlHelper, expression);
    

    The ASP.NET 5 equivalent is:

    Microsoft.AspNet.Mvc.Rendering.HtmlString html = 
         (Microsoft.AspNet.Mvc.Rendering.HtmlString)    
             Microsoft.AspNet.Mvc.Rendering.HtmlHelperInputExtensions.TextBoxFor(
                 htmlHelper, expression);
    

    or with the namespace included to your page

    @Microsoft.AspNet.Mvc.Rendering;
    

    it reads:

    HtmlString html = (HtmlString)HtmlHelperInputExtensions.TextBoxFor(htmlHelper,expression);
    

    Take note its return type is an interface IHtmlContent and not a MvcHtmlString as in ASP.NET 4.

    MvcHtmlString has been replaced with HtmlString in ASP.NET 5.

    Since an interface IHtmlContent of HtmlString is returned and not HtmlString itself you have to cast the return to HtmlString

    However you want to use this as an extension method in ASP.NET 5 so you should change your method return type to IHtmlContent and your code to:

     IHtmlContent html = HtmlHelperInputExtensions.TextBoxFor(htmlHelper,
                                              expression);
     return html;
    

    The source code can be found here.