Search code examples
asp.netcsshandheld

Apply different css based on device in asp.net?


I'm just starting to learn the basics of ASP.NET and have encountered a problem I don't know how to solve. I'm used to PHP and if I want a different css based on the device (Android or iPhone) used to browse my website i would do something like this:

<?php
#Check device used
$agent = $_SERVER['HTTP_USER_AGENT'];

if( strstr($agent, "Android") or strstr($agent, "iPhone") )
{
    echo("\t\t<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"handheld.css\" />\n");
    }
    else
    {
?>
        <link href="styles.css" rel="stylesheet" media="screen" type="text/css" />
<?php } ?>

But how is this done in asp.net? I have no clue. Thanx for listening.


Solution

  • Put this on your ASPX page:

    <% if(Request.UserAgent.contains("Android") { %>
    
       <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"handheld.css\" />
    
    <% } else { %>
    
       <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"regular.css\" />
    
    <% } %>
    

    You could do that in the code-behind to make it a bit cleaner.

    A suggestion would be to make the <head> tag runat="server", then run the above code in the Master page code behind to apply a different stylesheet.