【问题标题】:Imitating BeginForm() syntax模仿 BeginForm() 语法
【发布时间】:2012-09-26 02:05:47
【问题描述】:

我很好奇这是否可以通过 HtmlHelper 的设计来复制,或者它是否是 Razor 本身内置的特殊内容。

我正在为 Knockout 编写一个小型包装库,以摆脱使用 Fluent Interface approach 编写原始 html 的方式。但是,除非我可以执行以下操作,否则它将非常麻烦:

@using(Html.KoDiv().ForEach("MyArray").Visible("!Busy"))
{
     <some html here>
}

我所见过的唯一具有相似外观的是以下内容:

@using(Html.BeginForm("Action"))
{
    <some html here>
}

问题:我怎样才能摆脱这种语法?或者,还有其他我没有想到的轻量级语法方法吗?

我认为他们正在直接写入响应,或者可能调用 HtmlHelper.Raw() 并在 Dispose() 方法上呈现结束标记,因为您必须在他们的方法中使用 using 语句。然而,到目前为止,这些都没有奏效。有任何想法吗?谢谢!

示例代码:

 public class KoElement : IHtmlString, IDisposable
{
    protected StringBuilder m_sb;
    protected TagBuilder m_tagBuilder;
    protected List<string> m_events;


    public KoElement(TagBuilder tb, HtmlHelper html = null)
    {
        m_tagBuilder = tb;
        m_events = new List<string>();

    }

    public string ToHtmlString()
    {
        m_tagBuilder.Attributes.Add("data-bind", string.Join(", ", m_events));
        return m_tagBuilder.ToString(TagRenderMode.StartTag);
    }

    public void Dispose()
    {
         HttpContext.Current.Response.Write("</" + m_tagBuilder.TagName + ">");
    }

    public KoElement Visible(string expression)
    {
        if (!string.IsNullOrEmpty(expression))  
            m_events.Add(string.Format("visible: {0}", expression));
        return this;
    }

    public KoElement ForEach(string expression)
    {
        if (!string.IsNullOrEmpty(expression))
            m_events.Add(string.Format("foreach: {0}", expression));
        return this;
    }
}

【问题讨论】:

    标签: asp.net-mvc-3 razor html-helper


    【解决方案1】:

    您必须在 HTML Helper 中使用 ViewContext.Writer.Write(),而不是使用 HttpContext.Current.Response.Write()

    public class KoElement : IHtmlString, IDisposable
    {
        protected HtmlHelper m_html;
        protected TagBuilder m_tagBuilder;
        protected List<string> m_events;
    
        public KoElement(TagBuilder tb, HtmlHelper html)
        { 
            m_html = html;
            m_tagBuilder = tb;
            m_events = new List<string>();
        }
    
        public string ToHtmlString()
        {
            m_tagBuilder.Attributes.Add("data-bind", string.Join(", ", m_events));
            return m_tagBuilder.ToString(TagRenderMode.StartTag);
        }
    
        public void Dispose()
        {
            m_html.ViewContext.Writer.Write("</" + m_tagBuilder.TagName + ">");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-25
      • 2017-04-06
      • 1970-01-01
      • 2010-10-31
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多