views:

35

answers:

2

Hello,

I'm trying to add some share this javascript in between the head tags of an asp.net page but only if the page is not secure (!Request.IsSecureConnection). How do I get the code in the head tags to check for secure connection and then write the javascript if not secure. I've tried using <% %> blocks and RegisterStartupScriptBlock and it's not working

UPDATE:

Was able to get it to work using this in the Page_Load

if(!Request.IsSecureConnection)
{
    HtmlGenericControl Include = new HtmlGenericControl("script");
    Include.Attributes.Add("type", "text/javascript");
  Include.Attributes.Add("src", "http....");
  this.Page.Header.Controls.Add(Include);
}
A: 
<%if (!Request.IsSecureConnection)
{%>
    <script ..........> </script>
<%}%>

This didn't work?

Update From your comments this didn't work. I'm guessing it has to do with something you are doing in your code behind. Did you try calling RegisterClientScriptBlock from your code behind? If you could post your aspx and code behind we might be able to help more.

confusedGeek
No. I get this errorException of type 'System.Web.HttpUnhandledException' was thrown.; The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Put that stuff in the code-behind page instead of inline with the markup. Wrap a placeholder control or something similar around your script and show/hide the placeholder control based on secure connection or not.
John K
+1  A: 

This works for me:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <% if (!Request.IsSecureConnection)
       { %>
       <script type="text/javascript">
           onload = function() { 
                        alert('Page is not secure') };
       </script>
       <% } %>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>
Steve Danner