2012-09-26 48 views
3

我很好奇這是否可以通過HtmlHelper的設計複製,或者如果它是內置於Razor本身的特殊內容。模仿BeginForm()的語法

我正在爲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; 
    } 
} 

回答

3

而不是使用HttpContext.Current.Response.Write(),你在HTML輔助使用ViewContext.Writer.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 + ">"); 
    } 
}