.net 自定义html帮助程序:使用“创建帮助程序”;使用;语句支持

.net 自定义html帮助程序:使用“创建帮助程序”;使用;语句支持,.net,asp.net-mvc,html-helper,.net,Asp.net Mvc,Html Helper,我正在编写我的第一个asp.net mvc应用程序,我有一个关于自定义Html帮助程序的问题: 要制作表单,您可以使用: <% using (Html.BeginForm()) {%> *stuff here* <% } %> 进入: 这可能吗?如果您查看ASP.NET MVC的源代码(在上提供),您将看到Begin的实现最终调用以下代码: static MvcForm FormHelper(this HtmlHelper htmlHelper, string f

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

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

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


这可能吗?

如果您查看ASP.NET MVC的源代码(在上提供),您将看到Begin的实现最终调用以下代码:

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 FormHelper(此HtmlHelper HtmlHelper、字符串formAction、FormMethod方法、IDictionary htmlAttributes)
{
标记生成器=新标记生成器(“表格”);
builder.MergeAttributes(HtmlatAttributes);
builder.MergeAttribute(“动作”,形式);
builder.MergeAttribute(“方法”,HtmlHelper.GetFormMethodString(方法),true);
htmlHelper.ViewContext.HttpContext.Response.Write(builder.ToString(TagRenderMode.StartTag));
返回新的MvcForm(htmlHelper.ViewContext.HttpContext.Response);
}
MvcForm类实现IDisposable,在它的dispose方法中,它将数据写入响应


因此,您需要做的是在helper方法中写入您想要的标记,并返回一个实现IDisposable的对象…在它的dispose方法中关闭标记。

这里有一个可能的c#中的可重用实现:

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

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

我尝试遵循MVC3中给出的建议,但在使用时遇到了问题:

htmlHelper.ViewContext.HttpContext.Response.Write(...);
当我使用这段代码时,我的助手在呈现布局之前正在写入响应流。这不管用

相反,我用了这个:

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

嗯。。我觉得这会很容易。。谢谢你的努力。这只是一个快速而肮脏的实现。“begin”委托可以在您的扩展方法中直接调用,DisposableHelper类可用于其他扩展不确定这有什么不容易-这是一个非常优雅的解决方案。@ybo非常感谢您。我将其用于
Ajax.ActionLink
以支持htmlcontent,它现在提供了非常干净的代码。谢谢。为我节省了大量的时间。在MVC 3中为我工作时使用的原始代码是在html正文的正下方写出html助手内容。这把它修好了。
htmlHelper.ViewContext.HttpContext.Response.Write(s)
htmlHelper.ViewContext.HttpContext.Response.Write(...);
htmlHelper.ViewContext.Writer.Write(...);