从部分视图向视图头添加CSS,JS或其他内容 [英] Add css, js or other content to a views head from partial views

查看:61
本文介绍了从部分视图向视图头添加CSS,JS或其他内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些与此相关的问题,但是通常会有很多不同的答案,而且它们看起来都非常混乱和复杂.

I have found a few questions relating to this, but generally there are many different answers and they all seem very messy and complex.

如果这是需要做的,那么好吧,我最好坐下来解决它.

If that is what needs to be done, then ok i better sit down and tackle it.

我想知道最简单,最有效的方法是从局部视图向您的头部添加内容.

I want to know what the simplest and most efficient way is to add content to your head from partial views.

原因我需要执行此操作,因为我需要在每个页面上使用某些Java脚本和jquery,并且页面与页面之间存在差异.我不只是想将它们全部添加到_layout视图中.

Reason I need to do this is i need certain java script and jquery on each page and it differs from page to page. I donot just want to add them all in the _layout view.

推荐答案

您可以使用部分进行此操作.例如: 我有两个以上的视图,每个视图具有相同的_Layout.我在Company Controller中的Index操作具有以下部分:

You can do this with sections. For example: I have more than two view which each other has same _Layout.My Index action in Company Controller has a sections as follow:

@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>
}

和Invoice控制器中的显示操作"具有相同的部分,但具有不同的css和js,如下所示:

and Display Action in Invoice controller has same sections but different css and js as follow:

@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.看:

and then you can use this section in _Layout but its required argument should be false. Look at:

<!DOCTYPE html>
<html>
<head>
<!--usage-->
  @RenderSection("usage", required: false)
<!--other-->
  @RenderSection("other", required: false)
<!--script-->
  @RenderSection("script", required: false)
<head>
<body>
</body>
</html>

这篇关于从部分视图向视图头添加CSS,JS或其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆