开发者

Adding a script reference to the html head tag from a partial view

开发者 https://www.devze.com 2022-12-12 04:47 出处:网络
How do I inject a script tag such as <script src=\"somejsfile\"></script> or <script type=\"text/javascript>some javascript</script>

How do I inject a script tag such as

<script src="somejsfile"></script>

or

<script type="text/javascript>some javascript</script>

into the开发者_StackOverflow中文版 head tag of a page from a partial view?


Update: Answer for the old question This is about ASP.NET MVC. We can use the RenderSection. Here the sample for MVC 3 using Razor view engine:

layout view or master page:

<html>
  <head>
  <script ...></script>
  <link .../>
  @RenderSection("head")
  </head>
  <body>
  ...
  @RenderBody()
  ...
  </body>
</html>

View, e.g. Home:

@section head{
  <!-- Here is what you can inject the header -->
  <script ...></script>
  @MyClass.GenerateMoreScript()
}
<!-- Here is your home html where the @RenderBody() located in the layout. -->


Even if THX's answer works, it's not a good one as MVC's intention is to be stateless by nature. Moreover his solution does not let you place your scripts where they should go - most sites want their script declarations at the very bottom of their page just before the </body> tag as it is best for performance and search engine optimization.

There is an answer, thanks to Darin Dimitrov:

Using sections in Editor/Display templates

His answer allows you to register scripts from a partial view within the layout view.

The caveat is his answer marks items using a GUID in a dictionary object, so there is no guarantee the scripts will be rendered in the master page in the same order they are listed in your partial view.

There are two workarounds for that:

  1. Register only 1 script from a partial view -or-
  2. Change his HTML Helper implementation to support ordering

I'm trying to work on the later myself.

Good luck.


Partial views are UserControls. Can't you use RegisterClientScriptInclude method of ClientScriptManager?

protected override void OnLoad(EventArgs e) {
    base.OnLoad(e);
    Page.ClientScript.RegisterClientScriptInclude("some key", "http://website/javascript.js");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号