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

允我心安 提交于 2019-12-23 12:04:02

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/33362333/what-is-the-equivalent-of-system-web-mvc-html-inputextensions-in-asp-net-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!