loading javascript file in ASP.NET for a single page - asp.net

I'm using ASP.NET with a master page containing a script manager. I want to add a javascript file to only one page, but all pages inherit from the master. What is the proper way to accomplish this?
thanks in advance

Add a script manager proxy to the page you wish to add the javascript to and then add the javascript reference using the script manager proxy

In the Master Page add a content container in the HEAD section, in your page put the Javascript tag inside the instance of that container.
EDIT - for d03boy
On MasterPage:
<head runat="server">
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>
On ContentPage:
<asp:Content ID="LocalHeadContent" ContentPlaceHolderID="HeadContent" runat="server">
<script type="javascript" \>
</asp:Content>
For any content page that doesn't have something to include in the page header there's no need to even create the Content tag.

Can you just use the ClientScriptManager?
if (!Page.ClientScript.IsClientScriptIncludeRegistered("MyKey"))
{
Page.ClientScript.RegisterClientScriptInclude("MyKey", "~/js/script.js");
}

There are a couple of ways to accomplish what you are looking for.
1- put a content place holder in the section of your master page
<head runat="server">
<asp:ContentPlaceHolder runat="server" ID="JavascriptPlaceHolder">
</asp:ContentPlaceHolder>
</head>
and in the specific page you want to add a javascript file add:
<asp:Content ID="Content2" ContentPlaceHolderID="JavascriptPlaceHolder" Runat="Server">
<script type="text/javascript" src="myfile.js" ></script>
</asp:Content>
2- When you are not using Update Panels, use the ClientScript:
Page.ClientScript.RegisterClientScriptInclude("MyKey", "/myfile.js");
3- When using Update Panel and partial page rendering, use the ScriptManager object to register your javascript: (For a script that should be available for the onload event or at least be available when an update panel refreshes)
string javascript_string = "function myAlert(){ alert('me'); }";
ScriptManager.RegisterStartupScript(this, typeof(string), "MyKey", javascript_string, false);
Use the content place holder where you can, then use either other technique when you can't.

How to embed javascript into a content page?

Related

Referencing CSS Sheet in Aspx page with Master Page

Question is pretty well stated in the title. Normally I would use <link... /> to reference my CSS Sheet but since I'm using a master page I don't have access to the Head Tag so how do I reference a specific CSS sheet on my ASPX page. I tried using <%# Import Namespace="Style.css" but no luck. Thanks for the help.
Just add a CSS ContentPlaceHolder with a default value in it.
Basically, the CSS file you specify as default will be included unless you override that placeholder with an tag from a child page.
Your Master Page should look something like this.
<head>
<asp:ContentPlaceHolder ID="Stylesheets" runat="server">
<link rel="stylesheet" href="/css/master.css" type="text/css" />
</asp:ContentPlaceHolder>
</head>
Then from any pages using that Master Page, you can simply override that with a different stylesheet.
On (example) AboutUs.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="Stylesheets" runat="server">
<link rel="stylesheet" href="/css/Style.css" type="text/css" />
</asp:Content>
If you want to add a CSS stylesheet to any ASPX page, you should use PlaceHolders.
Master page: (in the section)
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
ASPX Page:
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
// add your link here
</asp:Content>
just drag your style sheet to your master page.aspx and it will work for all your other forms
You have 3 possible solutions:
Add your link to the head tag of the master page's markup. If you do so, all the pages using the given master page will automatically use your css file.
Use a ContentPlaceHolder in the head tag of your master page. You can use the ContentPlaceHolder at your pages referencing the given master page and you can add your link tag inside the ContentPlaceHolder tag in the markup.
You can add your link tag using Javascrip/jQuery functions.
Although I went the code behind route below in my Page_Load event (VB), I'll give the correct answer to A.K as it seemed to answer the question better but just didn't suit my specific case.
Dim link As New HtmlLink()
link.Attributes.Add("href", Page.ResolveClientUrl("../Css/Generic-Form2.css"))
link.Attributes.Add("Type", "text/css")
link.Attributes.Add("rel", "stylesheet")
Page.Header.Controls.Add(link)
Append the link tag to the head using DOM manipulation.

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

I am trying to add a panel as a child control of another panel in the codebehind of a master page, it's a simple as:
Panel1.Controls.Add(Panel2)
However when I try to do that, I get this error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
There are a number of questions that talk about having <%= %> elements in the head section, which I do not have. I have been so far as to remove all <% %> elements from this page, to no avail, the error still occurs. Can anyone suggest a way to get this to work?
* Example for Answer B *
=== code with error ===
<script type="text/javascript">
jQuery(document).ready(
function() {
alert('Hello!');
jQuery("#<%=TxtSampleId.ClientID %>").focus();
}
);
</script>
=== code without error ===
<asp:PlaceHolder id="dontCare" runat="server">
<script type="text/javascript">
jQuery(document).ready(
function() {
alert('Hello!');
jQuery("#<%=TxtSampleId.ClientID %>").focus();
}
);
</script>
</asp:PlaceHolder>
The "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)." error can be very annoying to say the least. It's a bug that Microsoft refuses to fix because there are workarounds. It happens when you try to dynamically load controls from the code behind, but your page source conflicts. Could be a few things going on...
Note: Stack Overflow doesn't handle syntax of code examples well, so I'll reference each answer with a letter, and in a later post, I'll attempt to type out an example. But I don't want to clutter this post because I want to get my points across.
A.) you have a <% Response.Write("something") %> in your page source. Or a <% CodeBehindMethod() %>. Remove it and be creative to populate it a different way!! One way is to place an ASP.NET Panel control (like a Panel ==> turns into a div tag when it renders to HTML) onto your page and dynamically populate the inner HTML attribute of that control. There are other ways of dealing with this.
B.) you are trying to use jQuery inside of an inline script block within your control, you will also get this. Surround the inline javascript code block with an ASP.NET PlaceHolder tag. It's that simple. If you don't, some jQuery functionality will work, but not all of it!
C.) If you are using Script Manager without a Masterpage, I'd suggest you start using a Masterpage to avoid issues later. Then use an ASP.NET ContentPlaceHolder for your head and your body tags to make customizing pages easier. When you reference your javascript files within your masterpage, and you're using Script Manager, make sure to put a Scripts tag inside your ScriptManager tag. Then inside the Scripts tag, place a ScriptReference tag with a Path of the full path of your Javascript files in there. Make sure to put a tilda and forward slash "~/" in the beginning of your path from the root of your web app. Many will put their ScriptManager tag in their control. Don't do this. Put it in your masterpage! It makes life easier.
D.) If A, B or C didn't answer your question, then I'd suggest stripping away every piece of your page and all controls in it, and add each one at a time. If you have a huge hierarchy of page and control inheritance (if your application doesn't have a Masterpage), good luck! You'll eventually figure out what caused it.
* Example for Answer C *
=== code without error ===
Masterpage code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><meta http-equiv="X-UA-Compatible" content="IE=7" />
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Stack Overflow Example</title>
<link rel="stylesheet" type="text/css" href="/style/jquery-ui-1.8.10.custom.css">
<asp:ContentPlaceHolder id="head" runat="server">
<asp:ContentPlaceHolder>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:ScriptManager ID="anything" runat="server">
<Scripts>
<asp:ScriptReference Path="~/scripts/md5.js" />
<asp:ScriptReference Path="~/scripts/jquery-1.4.4.min.js" />
<asp:ScriptReference Path="~/scripts/jquery-ui-1.8.10.custom.min.js" />
<asp:ScriptReference Path="~/custom_crap.js" />
</Scripts>
</asp:ScriptManager>
<asp:ContentPlaceHolder id="body" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>
</html>
====================================================
Page source:
<asp:Content runat="server" ID="headcontent" ContentPlaceHolderID="head">
.. place your page specific header files here (js, css, etc..)
</asp:Content>
<asp:Content runat="server" ID="bodycontent" ContentPlaceHolderID="body">
.. place your page specific body HTML or ASP.NET code here
</asp:Content>

How to Put Javascript into an ASP.NET MVC View

I'm really new to ASP.NET MVC, and I'm trying to integrate some Javascript into a website I'm making as a test of this technology.
My question is this: how can I insert Javascript code into a View?
Let's say that I start out with the default ASP.NET MVC template. In terms of Views, this creates a Master page, a "Home" View, and an "About" view. The "Home" View, called Index.aspx, looks like this:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
To learn more about ASP.NET MVC visit http://asp.net/mvc.
</p>
<p>Welcome to this testing site!</p>
</asp:Content>
Adding a <script> tag here didn't work. Where and how should I do it?
P.S.: I have a feeling I'm missing something very basic... Thanks in advance!
One thing you may want to consider is adding a "scripts" content place holder to your master page, that loads scripts at the end of the body. This way you load your scripts at the end of the page so that it doesn't slow down loading the DOM elements (once a script starts loading it only does one request at a time, because the code can affect the DOM). This gets a little tricky with PartialView -- if you include code in them you need to figure out a way to delay executing anything that relies on later scripts after those scripts have loaded. A compromise might be to load things like jQuery in the header and the rest of your common scripts at the end of the body.
Site.Master
<body>
...
<asp:ContentPlaceHolder runat="server" id="MainContent"></asp:ContentPlaceHolder>
...
<script type="text/javascript" src="<%= Url.Content( "~/scripts/jquery-1.4.1.min.js" ) %>"></script>
<asp:ContentPlaceHolder runat="server" id="ScriptContent"></asp:ContentPlaceHolder>
</body>
</html>
View
<asp:Content runat="server" ID="mainContent" ContentPlaceHolderID="MainContent">
... HTML ...
</asp:Content>
<asp:Content runat="server" ID="scriptContent" ContentPlaceHolderID="ScriptContent">
<script type="text/javascript">
$(function() {
$('.selector').click( function() {
...
});
});
</script>
</asp:Content>
Just stumbled on this question and would like add a comment that in Visual Studio 2013 it can be done in more elegant way.
In your master page just put the following code at the bottom of the page (in the default generated master page this code is already there):
<body>
...
#RenderSection("scripts", required: false)
</body>
</html>
Then in your view just at the bottom the following code:
#section scripts
{
<script src="...script url..."></script>
}
or if you use bundles
#section scripts {
#Scripts.Render("~/bundles/<script id>")
}
or you can put a <script>...</script> section with your Javascript code into the #section scripts block in the view.
Go create an additional <asp:ContentPlaceHolder> inside of the <head> of your masterpage and then your views will have a third <asp:Content> section for you to register external .js files, custom <script> blocks, external .css files, and custom <style> blocks.
The <script> tag needs to go inside an <asp:Content> block. (Otherwise, where would it end up?)

Do script tags and link tags go inside asp:content or outside

I have a page which has a masterpage. Do I put script and link tags inside the asp:content place holders or outside or does it matter.
When I put it outside, I get the following warning:
Only Content controls are allowed directly in a content page that contains Content controls.
I can see five (or 8) ways of doing it:
In the codebehind (.cs or .vb) using:
Scriptmanager.RegisterClientScriptinclude - using an absolute/relative path
Scriptmanager.RegisterClientScriptInclude - using an embedded resource
Scriptmanager.RegisterSlientScriptBlock - with your source inside
Adding it inline to your ASPX page in the designer
Sticking it inside the asp:content where the content lives inside the body tag.
Sticking it inside the asp:content where the content lives inside the head (You've said this isn't an option, so ignore this).
Adding it programmatically using the ScriptManager inside a control you use on the page as above.
"Only Content controls are allowed directly in a content page that contains Content controls" - did you forget the runat="server"?
If it's scripts and links for all pages, it should go outside any ContentPlaceHolders. If it's scripts and links for this page, it should go inside a Content inside the head. If it's default scripts, put it inside a head ContentPlaceHolder, and it can be replaced by the child page if needed. (VS usually complains about a ContentPlaceHolder in the head, but it works fine for me).
// master Page
<head runat="server">
<asp:ContentPlaceHolder id="head" runat="server">
<!-- Default scripts and CSS -->
<link rel="stylesheet" type="text/css" href="default.css" />
<script type="text/javascript" src="jquery.js"></script>
</asp:ContentPlaceHolder>
<!-- Mandatory scripts and css -->
<link rel="stylesheet" type="text/css" href="all.css" />
<script type="text/javascript" src="all.js"></script>
</head>
<body>
Master Page!
<asp:ContentPlaceHolder id="body" runat="server" />
</body>
// Child (no JQuery)
<asp:Content ContentPlaceHolderID="head" runat="server">
<link rel="stylesheet" type="text/css" href="default.css" />
<!-- Don't need JQuery -->
<script type="text/javascript" src="prototype.js"></script>
</asp:Content>
<asp:Content ContentPlaceHolderID="body" runat="server">
Child Page!
</asp:Content>
// Child 2 (with JQuery)
<asp:Content ContentPlaceHolderID="body" runat="server">
Child Page!
</asp:Content>
If you are referring to <asp:Content /> tags, you can't put anything outside of them in an .aspx page. So you're limited to putting them inside the <asp:Content /> tag. If you want <script /> and <link /> tags you need to either put a <asp:ContentPlaceHolder /> in the <head> of your master page, or add them dynamically via the Page's Controls collection.
Outside. Tthe inside of the ContentPlaceholders is going to be replaced with content from your pages anyhow so it doesn't make much sense to put anything in there.
outside. in the master page
The place holders are the wrapping controls for pages which descend from master pages.
Use asp.net scriptreference tag in master page to add reference to javascript file and you will be able to access all you need in the javascript file as if you would have added to the local page.

ASP.NET MVC - View with master page, how to set title?

What is prefered way of setting html title (in head) for view when using master pages?
One way is by using Page.Title in .aspx file, but that requires in master page which can mess with HTML code. So, lets assume no server side controls, only pure html. Any better ideas?
UPDATE: I would like to set title in view NOT in the controller or model.
In our master pages, we created both an "init" ContentPlaceHolder, and a "title" ContentPlaceHolder. If someone wants to programatically set Page.Title, they can set it in CSharp in the init placeholder, or they can override the "title" placeholder using tags.
Master Page
<asp:ContentPlaceHolder id="init" runat="server"></asp:ContentPlaceHolder>
<head runat="server">
<asp:ContentPlaceHolder ID="title" runat="server">
<title><%=this.Page.Title%></title>
</asp:ContentPlaceHolder>
</head>
View Page
Could either override the entire "title" content placeholder:
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
<title>Home Page</title>
</asp:Content>
or programatically set the page title.
<asp:Content ID="Content1" ContentPlaceHolderID="init" runat="server">
<%this.Title = "Home Page";%>
</asp:Content>
Make sure you remove the Title="" from the Page directive at the top, or you won't be able to programatically change Page.Title.
I see a lot of people that use the <%= ViewData["Title"] %> option.
I suppose you could also insert a ContentPlaceHolder named Title and then just use that on your page, but in all the MVC examples I've seen, they use the first option.
When I create a new MVC project it has files in there and uses a master page. Looking at that it seems it passes the title to the ViewData as ViewData["Title"] and in the master page, in the <head> there is a script block that outputs ViewData["Title"].
I ended up using a code-behind file to implement Page.Title="..." in the Page_Load() method.
I didn't like doing this, however attempts to implement the change directly in the .aspx page did not work, as it resulted in two <title> tags being present, the one I generated, and the one generated by the Master file the page inherited from.
Ideally, my page code should have overridden the master file's <title> value, but I guess this is just one of those quirks that ASP.Net MVC still has, and one that may already be fixed in a newer version of the ASP.Net MVC Framework (we're still on ASP.Net MVC Beta)
You could do this in your Master Page:
<title>
<%:MyTitle + " :: " %>
<asp:ContentPlaceHolder ID="TitleContent" runat="server">
</asp:ContentPlaceHolder>
</title>
where MyTitle = some value from your web.config or hard text like "My Web"
Now in the view pages (Index for example):
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<%:"My Home Page"%>
Now when you browse your home page, the title would be "My Web :: My Home Page".
I have a base view class that sets the page title from a resource file. Works pretty good for me.
I created a class called Application with a Title property (using get/set):
public static class Application
{
static string title;
public static string Title
{
get { return title; }
set { title = value; }
}
}
I then set the property on the Page_Load event for each page:
Application.Title = "Silly Application";
then i just reference that property on the master page:
<div id="divApplicationTitle">
<asp:HyperLink runat="server" NavigateUrl="~/Default.aspx"><asp:Image ID="imgApplicationImage" runat="server" SkinID="skinApplicationLogo" /><%=Application.Title%></asp:HyperLink>
</div>
There is a Title property of the #Page directive for content pages.
For ASP.NET content pages just add Title="" in the <%# %> Placeholder.
We ended up with
<head runat=server visible=false>
in master page.
This way we can read from Page.Title (Page.Title requires head element to exist, otherwise it throws an exception, checked that with reflector). We then use our own head element - MVC way.
You could always use javascript in your view page:
<script type="text/javascript>
document.title = "Hello World";
</script>

Resources