模仿BeginForm()语法

时间:2012-09-26 02:05:48

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

我很好奇这是否可以通过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;
    }
}

1 个答案:

答案 0 :(得分:3)

您必须在HTML帮助程序中使用HttpContext.Current.Response.Write(),而不是使用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 + ">");
    }
}
相关问题