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

前端 未结 2 1498
终归单人心
终归单人心 2021-01-22 04:17

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,

相关标签:
2条回答
  • 2021-01-22 05:01

    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>
        }
    
    0 讨论(0)
  • 2021-01-22 05:17

    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>
    
    0 讨论(0)
提交回复
热议问题