Is there a way to use a session variable in CSS style such as to set width % dynamically.
width:<%Convert.ToString(Session["DaysAvailable"]);%>%;
Is there a way to use a session variable in CSS style such as to set width % dynamically.
width:<%Convert.ToString(Session["DaysAvailable"]);%>%;
Yes, as @JB11 confirmed. Here's a working example.
PageLoad() only.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:
Note:This work only when CSS is directly inside the Page Markup and not in external Stylesheet.