0 Comments

If you want to set the visibility of a control based on some C# code like User.IsInRole("Administrator") directly in your *.aspx page, you can use the data binding syntax <%# … %> in the ASP .NET page. You don’t need the Eval function, but you do need to bind you’re page, else the code in  <%# … %> will not be executed.

If you use the <%# … %> syntax in your master page, you should call this.DataBind() in your Page_Load event, else the code in <%# … %> won’t be executed.

*.ASPX

<%@ Master  Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" 
            Inherits="Rvl.Demo.AspNet4.EF.WebApplication.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form runat="server">
    <div class="page">
        <asp:LinkButton ID="LinkButton1" runat="server" 
        Visible='<%# User.IsInRole("Administrator") %>'>This link will only be visible for Administrators</asp:LinkButton>       
    </div>
    </form>
</body>
</html>

*.cs

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

namespace Rvl.Demo.AspNet4.EF.WebApplication
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.DataBind();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts