如果您查看 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 方法中关闭标签。