如何将Visual Studio 2017 MVC视图脚手架更新为Bootstrap 4?
解决VS2017 MVC5脚手架生成Bootstrap4视图的问题
我之前升级Bootstrap版本时也遇到过一模一样的情况——VS2017自带的MVC5脚手架默认还是用Bootstrap3的CSS类,要让它生成Bootstrap4的代码,得手动修改脚手架的模板文件,具体操作如下:
方法一:修改全局脚手架模板(影响所有项目)
- 找到VS2017的模板安装路径,根据你的VS版本替换对应文件夹:
社区版路径示例:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates\MvcView
专业版/企业版把路径里的Community换成Professional或Enterprise - 先备份该文件夹下的所有
.cs.t4文件(比如Edit.cs.t4、Create.cs.t4、Details.cs.t4这些),防止改坏了没法恢复 - 打开需要修改的模板文件(比如你提到的编辑视图对应
Edit.cs.t4),把里面Bootstrap3的类替换成Bootstrap4的对应类:form-horizontal→ 改用Bootstrap4的网格布局,比如给form-group加上row类control-label→col-form-labelbtn-default→btn-secondaryhelp-block→form-text text-muted- 举个表单组的修改示例:
原BS3代码:
修改为BS4代码:<div class="form-group"> @Html.LabelFor(model => model.[PropertyName], htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.[PropertyName], new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.[PropertyName], "", new { @class = "text-danger" }) </div> </div><div class="form-group row"> @Html.LabelFor(model => model.[PropertyName], htmlAttributes: new { @class = "col-sm-2 col-form-label" }) <div class="col-sm-10"> @Html.EditorFor(model => model.[PropertyName], new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.[PropertyName], "", new { @class = "text-danger" }) </div> </div>
- 保存修改后的模板,重启Visual Studio,之后再通过脚手架添加视图时,生成的代码就会用Bootstrap4的类了
方法二:项目内自定义模板(仅影响当前项目)
如果你不想修改全局模板(避免影响其他项目),可以在当前项目内创建自定义模板:
- 在项目根目录新建
CodeTemplates\MvcView文件夹结构,比如要修改编辑视图,就创建CodeTemplates\MvcView\Edit文件夹 - 把之前备份并修改好的
Edit.cs.t4文件复制到这个文件夹里 - Visual Studio会优先读取项目内的
CodeTemplates文件夹中的模板,之后生成视图时就会用你自定义的Bootstrap4模板了
内容的提问来源于stack exchange,提问作者xr280xr
相关产品推荐
相关产品推荐

