如何避免在MVC视图中重复编写相同的Scripts和Styles代码块
当然可以!这在ASP.NET MVC 5里是非常常见的复用场景,我们可以通过**局部视图(Partial View)**来封装这些重复的@section代码块,实现按需引用,完美解决重复代码的问题,后续修改也只需要改一处就行。下面给你详细的实现方案:
步骤1:创建局部视图
在Views/Shared目录下新建一个局部视图,比如命名为_DataTablesDependencies.cshtml,把你重复的styles和scripts section代码放进去:
@section styles { <link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" /> <link href="~/Content/DataTables/css/buttons.dataTables.css" rel="stylesheet" /> } @section scripts { <script src="~/Scripts/DataTables/jquery.dataTables.js"></script> <script src="~/Scripts/DataTables/dataTables.buttons.js"></script> <script src="~/Scripts/DataTables/buttons.print.js"></script> <script src="~/Scripts/DataTables/buttons.html5.js"></script> <script src="~/Scripts/jszip.js"></script> <script> $(() => { // source js file defined in BundleConfig.cs TableController.init(); }); </script> }
步骤2:在需要的视图中引用局部视图
在任何需要加载这些DataTables资源的视图里,只需要添加一行代码就能引入整个section块:
@{ Html.RenderPartial("_DataTablesDependencies"); }
也可以用@Html.Partial("_DataTablesDependencies"),两者的区别是RenderPartial会直接将内容输出到响应流,性能略优;Partial会返回一个MvcHtmlString,效果上在视图里使用差别不大,根据习惯选择即可。
为了进一步优化加载性能,你可以把这些DataTables的CSS和JS文件打包成Bundle,这样不仅减少HTTP请求数,维护起来也更方便。
步骤1:在BundleConfig.cs中配置Bundle
打开App_Start/BundleConfig.cs,添加DataTables的样式和脚本Bundle:
public static void RegisterBundles(BundleCollection bundles) { // 保留原有的其他Bundle配置... // 配置DataTables样式Bundle bundles.Add(new StyleBundle("~/bundles/datatables/css") .Include("~/Content/DataTables/css/jquery.dataTables.css") .Include("~/Content/DataTables/css/buttons.dataTables.css")); // 配置DataTables脚本Bundle bundles.Add(new ScriptBundle("~/bundles/datatables/js") .Include("~/Scripts/DataTables/jquery.dataTables.js") .Include("~/Scripts/DataTables/dataTables.buttons.js") .Include("~/Scripts/DataTables/buttons.print.js") .Include("~/Scripts/DataTables/buttons.html5.js") .Include("~/Scripts/jszip.js")); }
步骤2:修改局部视图使用Bundle引用
把之前的局部视图代码替换成Bundle的渲染语句:
@section styles { @Styles.Render("~/bundles/datatables/css") } @section scripts { @Scripts.Render("~/bundles/datatables/js") <script> $(() => { // source js file defined in BundleConfig.cs TableController.init(); }); </script> }
这样以后要添加或移除DataTables的资源,只需要修改BundleConfig里的配置就行,不用改每个视图或者局部视图。
MVC的局部视图在渲染时会继承主视图的上下文,所以局部视图里定义的@section会被主视图的布局页面识别,布局里的@RenderSection("styles", required: false)和@RenderSection("scripts", required: false)会正确渲染这些内容,完全不用担心不会生效的问题。而且这种方式完全满足你的需求——只有引用了局部视图的视图才会加载这些资源,不会影响其他不需要的视图。
内容的提问来源于stack exchange,提问作者RandomHandle

