我能否在WebForms项目中像ASP.NET MVC一样创建HTML辅助程序?

4

我能在Webforms项目中像在asp.net mvc中一样创建html helpers吗?谢谢。


你能举个例子说明你想要什么以及为什么想要吗? - John Saunders
3个回答

4
这是目前在我有限的使用中有效的一个:
public static class PageCommon
{
   public static System.Web.Mvc.UrlHelper GetUrlHelper(this System.Web.UI.Control c)
   {
       var helper = new System.Web.Mvc.UrlHelper(c.Page.Request.RequestContext);
       return helper;
   }
   class ViewDataBag : IViewDataContainer
   {
        ViewDataDictionary vdd = new ViewDataDictionary();
        public ViewDataDictionary ViewData
        {
            get
            {
                return vdd;
            }
            set
            {
                vdd = value;
            }
        }
    }
    public static System.Web.Mvc.HtmlHelper GetHtmlHelper(this System.Web.UI.Control c)
    {
        var v = new System.Web.Mvc.ViewContext();
        var helper = new System.Web.Mvc.HtmlHelper(v, new ViewDataBag());
        return helper;
    }

这个答案在很大程度上弥合了一个鸿沟,使MVC Html语句(如Html.DisplayFor等)得以实现。 - enorl76
System.Web.Mvc.UrlHelper在WebForms中的使用?有完整的示例WebForms aspx页面吗? - PreguntonCojoneroCabrón

2
你只需要一个静态方法:
public static string Label(string target, string text)
{
    return String.Format("<label for= '{0}'>{1}</label>",target,text);
}

1

如果你想返回WebControls,那么它不会像添加静态方法那样简单。你需要连接到页面渲染。


不仅如此,您还需要创建自己的智能感知,以便轻松使用HTML助手(这是HTML助手的全部意义所在)。 - Sean Haddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接