I want to write a basic if statement on my web-application, as I would like to place <script>
based on a condition in .aspx page, how can I achieve it?
Something like
if(Condition)
{
//script here
}
else
{
}
here is my script, that i want to place
<script type="text/javascript">
function openColorBox() {
$.colorbox({
innerWidth:400,
innerHeight:300,
iframe:true,
href: "rating_page.aspx",
overlayClose:true,
onLoad: function() {
// $('#cboxClose').remove();
// $.colorbox({ overlayClose: true });
}
});
}
// openColorBox.Stop()
setTimeout(openColorBox, 1000);
</script>
You can place if-condition in .aspx pages using the code below
<%
if(condition)
{%>
//Your script or html here
<% }
else
{
%>
//Your script or html here
<% } %>
I hope this helps, thanks
Check this code , it may help you
.aspx code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Example Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%if (i == 1) { %>
<asp:Label ID="Label1" runat="server" Text="If Bloc"></asp:Label><br />
//Script code here
<%} %>
<%else { %>
<asp:Label ID="Label2" runat="server" Text="Else Block"></asp:Label>
//Script code here
<%} %>
</div>
</form>
</body>
</html>
C# Code in code behind
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
public int i;
protected void Page_Load(object sender, EventArgs e)
{
i = 1;
}
}
You can simply wrap markup in a condition as below
<% if(somecondition) { %>
some html
<% } %>
OR
On page load check this
if (variableOrCondition) {
Item1.Visible = true;
Item2.Visible = false;
} else {
Item1.Visible = false;
Item2.Visible = true;
}
These are two easy solutions.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly