39

我正在编写我的第一个 asp.net mvc 应用程序,我有一个关于自定义 Html 助手的问题:

要制作表格,您可以使用:

<% using (Html.BeginForm()) {%>
   *stuff here*
<% } %>

我想用自定义 HTML 助手做类似的事情。换句话说,我想改变:

Html.BeginTr();
Html.Td(day.Description);
Html.EndTr();

进入:

using Html.BeginTr(){
    Html.Td(day.Description);
}

这可能吗?

4

3 回答 3

49

这是 c# 中可能的可重用实现:

class DisposableHelper : IDisposable
{
    private Action end;

    // When the object is created, write "begin" function
    public DisposableHelper(Action begin, Action end)
    {
        this.end = end;
        begin();
    }

    // When the object is disposed (end of using block), write "end" function
    public void Dispose()
    {
        end();
    }
}

public static class DisposableExtensions
{
    public static IDisposable DisposableTr(this HtmlHelper htmlHelper)
    {
        return new DisposableHelper(
            () => htmlHelper.BeginTr(),
            () => htmlHelper.EndTr()
        );
    }
}

在这种情况下,BeginTr直接EndTr写入响应流。如果您使用返回字符串的扩展方法,则必须使用以下命令输出它们:

htmlHelper.ViewContext.HttpContext.Response.Write(s)
于 2009-03-24T10:39:54.993 回答
33

我尝试按照 MVC3 中给出的建议进行操作,但在使用时遇到了麻烦:

htmlHelper.ViewContext.HttpContext.Response.Write(...);

当我使用这段代码时,我的助手在我的布局被渲染之前写入响应流。这效果不好。

相反,我使用了这个:

htmlHelper.ViewContext.Writer.Write(...);
于 2011-05-19T21:47:29.177 回答
19

如果您查看 ASP.NET MVC 的源代码(可在Codeplex上获得),您将看到 BeginForm 的实现最终会调用以下代码:

static MvcForm FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
{
    TagBuilder builder = new TagBuilder("form");
    builder.MergeAttributes<string, object>(htmlAttributes);
    builder.MergeAttribute("action", formAction);
    builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
    htmlHelper.ViewContext.HttpContext.Response.Write(builder.ToString(TagRenderMode.StartTag));

    return new MvcForm(htmlHelper.ViewContext.HttpContext.Response);
}

MvcForm 类实现了 IDisposable,在它的 dispose 方法中将 </form> 写入响应。

因此,您需要做的是在辅助方法中编写您想要的标签并返回一个实现 IDisposable 的对象......在它的 dispose 方法中关闭标签。

于 2009-03-24T10:38:24.887 回答