这看起来有点愚蠢,但它仍然是我想要学习的东西。
现在,在 ASP.NET MVC 3.0 中,您需要使用语法 @using (Html.BeginForm()) {
然后是 }
关闭一个表单块以获得新的“不引人注目的 javascript”,以免您想手工编写所有内容(这很好)。
出于某种原因( Read: *OCD*
)我不喜欢那样。我真的宁愿这样做..
@Html.BeginForm()
<div class="happy-css">
</div>
@Html.EndForm()
看起来还傻吗?是的,每个人都有自己的。我想了解为什么它是这样工作的,并根据我的喜好塑造它。所以我想我要开始挖掘的第一个地方是 MVC 3.0 源代码本身。所以我跳入 codeplex 找到了
BeginForm
扩展方法。( http://aspnet.codeplex.com/SourceControl/changeset/view/63452#288009 )
所以现在我对如何开始实现我的目标有点困惑。通读代码,我发现它们都归结为一个根方法(这并不奇怪,因为大多数扩展方法似乎都是分层方法,所有方法都向下延伸到一个单一的方法以避免冗余)。
private static MvcForm FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes) {
TagBuilder tagBuilder = new TagBuilder("form");
tagBuilder.MergeAttributes(htmlAttributes);
// action is implicitly generated, so htmlAttributes take precedence.
tagBuilder.MergeAttribute("action", formAction);
// method is an explicit parameter, so it takes precedence over the htmlAttributes.
tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
HttpResponseBase httpResponse = htmlHelper.ViewContext.HttpContext.Response;
httpResponse.Write(tagBuilder.ToString(TagRenderMode.StartTag));
return new MvcForm(htmlHelper.ViewContext.HttpContext.Response);
}
我在这里没有看到的是这种方法与不显眼的 javascript 有何关系。如果我只是输入..
<form action="/Controller/Action" method="post">
然后像这样输入我的验证......
@Html.ValidationSummary(false)
我没有得到不显眼的 javascript。但如果我使用
@using (Html.BeginForm()) {
那我做。我什至检查了生成的标记,我真的找不到区别。现在它变得奇怪了。如果我只是输入...
@Html.BeginForm()
然后把我所有的表单代码,表单作品 我得到了不显眼的 javascript,但我必须手动输入 </form>
在末尾。 @Html.EndForm()
不起作用。但除此之外,我现在得到文本 System.Web.Mvc.Html.MvcForm
写入 <form action="/Controller/Action" method="post">
正下方的输出流html。有人可以启发和/或帮助我吗?
最佳答案
您的基本问题(即如何使用 BeginForm/EndForm 语法)的答案是按以下方式进行:
@{ Html.BeginForm(...); }
<div> content</div>
@{ Html.EndForm(); }
不幸的是,在调用写入输出的助手时,现在的 Razor 语法有点冗长(与大多数只返回 html 片段的助手相反)。您可能可以通过编写自己的扩展方法来使这更容易,如下所示:
public static IHtmlString FormBegin(this HtmlHelper helper, ...) {
helper.BeginForm(...);
return new HtmlString("");
}
public static IHtmlString FormEnd(this HtmlHelper helper) {
helper.EndForm();
return new HtmlString("");
}
关于asp.net-mvc-3 - 在 MVC 3.0 中重写 Html.BeginForm() 并保持不显眼的 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5092761/