我在写我的第一个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);
}

这是可能的?

有帮助吗?

解决方案

下面是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()
        );
    }
}

在这种情况下,BeginTrEndTr直接在响应流写入。如果您使用扩展方法返回一个字符串,你使用必须将他们输出:

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

其他提示

我试着按照MVC3这里给出的建议,但我遇到了麻烦使用:

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

当我用这个代码,我的助手被写入到响应流之前我的布局被渲染。这并没有很好地工作。

相反,我使用这样的:

htmlHelper.ViewContext.Writer.Write(...);

如果你看看来源为ASP.NET MVC(可在 Codeplex上),你” LL看到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,在它的处置方法写入到响应中。

那么,你需要做的是写你的helper方法想出来的标签,并返回实现IDisposable的对象......在它的Dispose方法关闭标签了。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top