如何为.aspx视图应用Bootstrap样式?仅在视图中设置DropDownList样式(不修改模型)
没问题!要在视图层给DropDownList添加Bootstrap样式,完全不用改动模型层——只需要利用Html.DropDownList的重载方法,传入HTML属性参数即可。
Bootstrap的表单控件核心样式是form-control,我们只需要把这个类名通过htmlAttributes参数传递给DropDownList控件就行。以下是修改后的完整代码片段:
<% using (Html.BeginForm(FormMethod.Post)) { %> <%: Html.ValidationSummary(true) %> <div class="form-group"> <div class="row"> <div class="col-md-6 text-right"> Pais: </div> <div class="col-sm-6"> <!-- 关键修改:添加了htmlAttributes参数,指定Bootstrap的form-control类 --> <%: Html.DropDownList("CodPais", String.Empty, new { @class = "form-control" }) %> <!-- 可选优化:把原来的label label-danger换成Bootstrap更适配的text-danger类 --> <p class="text-danger"><%: Html.ValidationMessageFor(model => model.CodPais) %></p> </div> </div> </div> <% } %>
几点说明:
new { @class = "form-control" }:这里的@class是因为class是C#的保留关键字,必须加@转义,最终渲染到HTML里会变成class="form-control",这正是Bootstrap识别的表单控件样式。- 别忘了确保你的页面已经引入了Bootstrap的CSS文件(通常放在
<head>标签里),否则样式不会生效。 - 我把错误提示的
label label-danger改成了text-danger,这是Bootstrap中用于文本错误提示的标准类,如果你想保留原来的样式也可以不改,不影响DropDownList的核心样式设置。
内容的提问来源于stack exchange,提问作者rodrigo.rodriguez
相关产品推荐
相关产品推荐

