twitter-bootstrap 如何在 MVC3/4 中向 Html.BeginForm() 添加类属性以保留最小重载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12925789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add a class attribute to Html.BeginForm() in MVC3/4 preserving the minimal overload
提问by Ralph Lavelle
I'm in the process of upgrading my app to Bootstrap 2.1.1 and I need to add a class attribute (class="form-horizontal") to many of the form tags. The problem is, most of the forms use the rather beautiful
我正在将我的应用程序升级到 Bootstrap 2.1.1,我需要向许多表单标签添加一个类属性 (class="form-horizontal")。问题是,大多数表格都使用了相当漂亮的
@using (Html.BeginForm()) {
format which I'd rather keep. The obvious way to get the class attribute in there is to use the following overload, for example:
我宁愿保留的格式。获取类属性的明显方法是使用以下重载,例如:
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal" })) {
But I'd rather not do that. What is the best way to add a class attribute to my form?
但我宁愿不这样做。将类属性添加到我的表单的最佳方法是什么?
I've thought about using a jQuerydocument ready handler to .addClass("form-horizontal") to forms, but am worried that users would see the dreaded 'flash of unstyled content'.
我曾考虑使用jQuery文档就绪处理程序将 .addClass("form-horizontal") 用于表单,但我担心用户会看到可怕的“无样式内容闪烁”。
Another approach might be to use a less-style mix-in, to add the .form-horizontal class to all form style rules but I haven't used less yet, so I'm not sure about this one.
另一种方法可能是使用较少风格的混合,将 .form-horizontal 类添加到所有表单样式规则,但我还没有使用过less,所以我不确定这个。
Anyone know the best way to solve this problem?
有谁知道解决这个问题的最佳方法?
回答by Ralph Lavelle
Following StanK's advice, and the advice of some other answers on SO, I created an extension method specifically tailored to that Bootstrap form layout:
按照 StanK 的建议以及其他一些关于 SO 的答案的建议,我创建了一个专门针对 Bootstrap 表单布局定制的扩展方法:
public static MvcForm BeginHorizontalForm(this HtmlHelper helper) {
return helper.BeginForm(null, null, FormMethod.Post, new { @class = "form-horizontal" });
}
which allows me to use
这让我可以使用
@using (Html.BeginHorizontalForm()) {...
which is nice and elegant.
这是好的和优雅的。
回答by StanK
What about writing a custom helper method which calls the overload required, passing in 'form-horizontal'?
编写一个调用所需重载的自定义帮助器方法,传入“form-horizontal”怎么样?
Then, you views would use @using (Html.BootstrapBeginForm()) {, leaving you views nice and tidy.
然后,您的视图将使用@using (Html.BootstrapBeginForm()) {,让您的视图整洁。

