我發現了一些與此有關的問題,但通常有許多不同的答案,它們都顯得非常混亂和複雜。將css,js或其他內容添加到部分視圖的視圖頭
如果這是需要做的,那麼好吧,我最好坐下來解決它。
我想知道最簡單和最有效的方法是從部分視圖向頭部添加內容。
我需要這樣做的原因是我需要在每個頁面上使用特定的Java腳本和jQuery,並且每頁都有所不同。我不想將它們全部添加到_layout視圖中。
我發現了一些與此有關的問題,但通常有許多不同的答案,它們都顯得非常混亂和複雜。將css,js或其他內容添加到部分視圖的視圖頭
如果這是需要做的,那麼好吧,我最好坐下來解決它。
我想知道最簡單和最有效的方法是從部分視圖向頭部添加內容。
我需要這樣做的原因是我需要在每個頁面上使用特定的Java腳本和jQuery,並且每頁都有所不同。我不想將它們全部添加到_layout視圖中。
您可以使用章節進行此操作。例如: 我有兩個以上的視圖,其彼此具有在公司控制器相同_Layout.My索引操作有一個部分如下:在發票控制器
@model Invoice.Model.HelperClasses.CompanyViewModel
@{
ViewBag.Title = "Companies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section usage{
<link href="~/css/uniform.default.css" rel="stylesheet" />
}
@section other{
<link href="~/css/datepicker.css" rel="stylesheet" />
<link href="~/css/SimpleSlide.css" rel="stylesheet" />
<link href="~/css/responsive-tables.css" rel="stylesheet" />
}
@section script
{
<script src="~/js/datepicker/bootstrap-datepicker.js"></script>
}
和顯示屏操作具有相同的部分,但不同的CSS和JS如下所示:
@model Invoice.Model.HelperClasses.InvoiceViewModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section usage{
@*<link href="~/css/uniform.default.css" rel="stylesheet" />*@
}
@section other{
<link href="~/css/DT_bootstrap.css" rel="stylesheet" />
<link href="~/css/responsive-tables.css" rel="stylesheet" />
<script src="~/js/datatables/extras/ZeroClipboard.js"></script>
}
@section script
{
<script src="~/js/datepicker/bootstrap-datepicker.js"></script>
<script src="~/js/validate/jquery.metadata.js"></script>
<script src="~/js/validate/jquery.validate.js"></script>
}
然後您可以在_Layout中使用此部分,但其必需的參數應該爲false。請看:
<!DOCTYPE html>
<html>
<head>
<!--usage-->
@RenderSection("usage", required: false)
<!--other-->
@RenderSection("other", required: false)
<!--script-->
@RenderSection("script", required: false)
<head>
<body>
</body>
</html>
在您_Layout.cshtml頁面(或任何其他母版頁)使用下面的<head></head>
標籤的內部代碼。
@if (IsSectionDefined("SpecialOther"))
{
@RenderSection("SpecialOther")
}
在你想要特殊的CSS,腳本或任何其他項目的頁面上,指定它們的引用。例如,
@section SpecialOther{
<link href="~/css/responsive-tables.css" rel="stylesheet" />
<script src="~/js/datatables/extras/ZeroClipboard.js"></script>
}
感謝這個解決方案,我會試試看,能否請您給我解釋的區別「@」部分的使用和「@」等章節 – Zapnologica
歡迎您。如果它適合你,你能否將答案標記爲已接受。 :)。用法是您將在每個視圖中使用它的部分,但不是必需的,其他部分 - 它屬於視圖。所以,名稱'使用'和'其他'是正式名稱,您可以將其作爲指示特定CSS和JS鏈接的變量。 –