0

Is there a way to use a session variable in CSS style such as to set width % dynamically.

    width:<%Convert.ToString(Session["DaysAvailable"]);%>%;
2
  • 2
    If the style is embedded in the HTML, sure. If it's a separate .css file, no. Commented Jun 18, 2018 at 21:52
  • If this sort of thing is important to your project, you might want to look into LESS or SASS. Commented Jun 18, 2018 at 22:58

1 Answer 1

1

Yes, as @JB11 confirmed. Here's a working example.

  1. The div's width is set to 25% on PageLoad() only.
  2. It's set to 75% on button Click() event.

SessionCSS.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SessionCSS.aspx.cs" Inherits="SessionCSS" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>    
    <style>
        .my-class{
            background-color: green;
            color: white;
            width: <%= Session["DaysAvailable"].ToString() %>%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">    

        <div class="my-class">
            Days available
        </div>
        <br/>
        <asp:Button ID="btnUpdateDays" runat="server" Text="Update days" OnClick="btnUpdateDays_Click" />
    </form>
</body>
</html>

SessionCSS.cs (code behind)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SessionCSS : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if( !Page.IsPostBack)
        {
            Session["DaysAvailable"] = 25;
        }
    }

    protected void btnUpdateDays_Click(object sender, EventArgs e)
    {
        Session["DaysAvailable"] = 75;
    }
}

Result:

enter image description here

Note:This work only when CSS is directly inside the Page Markup and not in external Stylesheet.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.