Add css, js or other content to a views head from

2019-02-27 14:47发布

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.

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.

2条回答
SAY GOODBYE
2楼-- · 2019-02-27 15:35

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

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

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>
查看更多
我命由我不由天
3楼-- · 2019-02-27 15:38

On your _Layout.cshtml page (Or any other master page) Use following code on inside of <head></head> tag.

@if (IsSectionDefined("SpecialOther"))
{
    @RenderSection("SpecialOther")
}

On the page that you want special css,script or any other item, specify their refernces. e.g.,

    @section SpecialOther{
        <link href="~/css/responsive-tables.css" rel="stylesheet" />
  <script src="~/js/datatables/extras/ZeroClipboard.js"></script>
    }
查看更多
登录 后发表回答