为了账号安全,请及时绑定邮箱和手机立即绑定

将CSS或JavaScript文件从视图或局部视图添加到布局头

将CSS或JavaScript文件从视图或局部视图添加到布局头

交互式爱情 2019-12-09 09:57:25
版面页面头:<head>    <link href="@Url.Content("~/Content/themes/base/Site.css")"          rel="stylesheet" type="text/css" /></head>应用程序中的视图(AnotherView)需要:<link href="@Url.Content("~/Content/themes/base/AnotherPage.css")"      rel="stylesheet" type="text/css" />AnotherView有一个局部视图(AnotherPartial),它需要:<link href="@Url.Content("~/Content/themes/base/AnotherPartial.css")"      rel="stylesheet" type="text/css" />问题:如何添加这些CSS文件链接到布局头的AnotherView和AnotherPartial链接?RenderSection不是一个好主意,因为AnotherPage可以有多个Partials。将所有CSS添加到头部是没有用的,因为它会动态更改(取决于Anotherpages)。
查看完整描述

3 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

布局:


<html>

    <head>

        <meta charset="utf-8" />

        <title>@ViewBag.Title</title>

        <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

        <script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>

        <script src="@Url.Content("~/Scripts/modernizr-2.0.6-development-only.js")" type="text/javascript"></script>

        @if (IsSectionDefined("AddToHead"))

        {

            @RenderSection("AddToHead", required: false)

        }


        @RenderSection("AddToHeadAnotherWay", required: false)

    </head>

视图:


@model ProjectsExt.Models.DirectoryObject


@section AddToHead{

    <link href="@Url.Content("~/Content/Upload.css")" rel="stylesheet" type="text/css" />

}


查看完整回答
反对 回复 2019-12-09
?
慕斯709654

TA贡献1840条经验 获得超5个赞

遗憾的是,默认情况下无法将其section用作其他用户建议,因为a section仅可用于a的立即child数View。


但是,有效的是在每个视图中实现和重新定义section,这意味着:


section Head

{

    @RenderSection("Head", false)

}

这样,每个视图都可以实现头部,而不仅仅是直接子视图。但是,这仅部分起作用,特别是对于多个部分,麻烦就开始出现了(正如您在问题中提到的)。


因此,真正解决问题的唯一方法是使用ViewBag。最好的可能是CSS和脚本的单独集合(列表)。为此,您需要确保List在执行任何视图之前初始化了used。然后,您可以在每个视图/部分视图的顶部执行以下操作(如果Scriptsor Styles值为null,则无需关心:


ViewBag.Scripts.Add("myscript.js");

ViewBag.Styles.Add("mystyle.css");

然后,您可以在布局中循环浏览集合,并根据中的值添加样式List。


@foreach (var script in ViewBag.Scripts)

{

    <script type="text/javascript" src="@script"></script>

}

@foreach (var style in ViewBag.Styles)

{

    <link href="@style" rel="stylesheet" type="text/css" />

}

我认为这很丑陋,但这是唯一可行的方法。


****** UPDATE ****由于它首先开始执行内部视图并逐步处理布局,而CSS样式是级联的,因此通过反向样式列表可能是有意义的ViewBag.Styles.Reverse()。


这样,首先添加最外部的样式,这与CSS样式表的工作方式一致。


查看完整回答
反对 回复 2019-12-09
  • 3 回答
  • 0 关注
  • 470 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信