Hidalgo
Hidalgo

Reputation: 941

Where to write jQuery script in ASP.NET page?

I am working in VS2012 on ASP.NET Web Forms project. The project has Site.Master page which is used for all pages. I can add script to the Site.Master where I can write jQuery function; no problem. But how and where do you place iQuery script if I want it in a certain page of the project? The page (because it uses Site.Master) does not have Head section but has only one section:

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">

If I write script before the above line I get VS problem "Only Content controls are allowed directly in contect page ..."

So where would I put the jQuery script specific to one page?

Upvotes: 1

Views: 2996

Answers (3)

mayabelle
mayabelle

Reputation: 10014

You can add it programmatically like this from your page_load function:

HtmlGenericControl include = new HtmlGenericControl("script"); 
Include.Attributes.Add("type", "text/javascript"); 
Include.Attributes.Add("src", yourUrl); 
this.Page.Header.Controls.Add(include);

Upvotes: 0

Avitus
Avitus

Reputation: 15958

What you have to do is modify your site master page to have a content placeholder in the head section of the master page. Then in your regular aspx page that uses the master page put an asp:content object and then in the content object place your javascript code.

So you'll need a in your master page head:

<asp:ContentPlaceHolder ID="head" runat="server" />

and in your aspx page:

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">

</asp:Content>

But if you are looking for better performance I would put your scripts at the bottom of the page. You can read more about this here: http://developer.yahoo.com/performance/rules.html#js_bottom

Upvotes: 3

Wilfredo P
Wilfredo P

Reputation: 4076

You can put the Jquery into the asp:content for example:

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">

<script>
//Your Jquery
</script>
</asp:Content>

The only that you will need register the Jquery libray in the Master page that the page will use.

I hope that helps.

Upvotes: 1

Related Questions