Nitin Kumar Mishra
Nitin Kumar Mishra

Reputation: 315

How to change the Markup of a asp.net page serverside (from .cs file)

Thanks in advance.

We need to include or exclude IE conditional statements (which are in the header of the page) depending upon if a method(from the code behind) returns true or false. The Method is written in the code behind so if IfBrowserIsMobile() returns true , Markup related to IE conditional statement should not be present. How do we achieve this ? The Mark-up(in the header) is as follows-

<!--[if lt IE 9]>
    <link rel="stylesheet" href="/css/lt-ie9.css" media="screen"/>
    <![endif]-->

Upvotes: 3

Views: 198

Answers (2)

Sunil
Sunil

Reputation: 21396

Include a literal control in head section of your aspx page and then in code behind you can set the Text property of this control to anything you like. This text could be html or non-html text. You can have as many such controls in the head section as you feel is necessary for your requirements.

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

In your situation you can include following code also in Page_Load event.

protected void Page_Load(object sender, EventArgs e) 
{
  if(!Page.IsPostBack && !IfBrowserIsMobile())
  {
      Literal1.Text  = "<!--[if lt IE 9]>
    <link rel="stylesheet" href="/css/lt-ie9.css" media="screen"/>
    <![endif]-->";

  }

}

If you want to emit JavaScript using a Literal control then use code-behind like below. The important thing is to include opening and closing script tags in this case.

Literal1.Text = @"<script type='text/javascript'>alert('hello sir');</script>";

Upvotes: 4

David
David

Reputation: 218828

Wrap it in an element which itself doesn't emit any markup, such as a PlaceHolder:

<asp:PlaceHolder runat="server" ID="ieLogic">
    <!-- your client-side markup here -->
</asp:PlaceHolder>

Then in server-side code, just set its visibility depending on your condition:

if (IfBrowserIsMobile())
    isLogic.Visible = false;

Generally you don't change the markup from server-side code, but you can conditionally show/hide different parts of the markup.

Upvotes: 0

Related Questions