分配按钮的Visible属性为一个静态方法结果 [英] Assigning Visible Property of the Button to a Static Method Result

查看:164
本文介绍了分配按钮的Visible属性为一个静态方法结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图隐藏基于使用以下code用户的角色按钮:

I am trying to hide the button based on the user's role using the following code:

 <asp:Button ID="btndisplayrole" Text="Admin Button" Visible='<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' runat="server" OnClick="DisplayRoleClick" />

但是当我运行上面的code我收到以下错误信息:

But when I run the above code I get the following error message:

不能从它的字符串重新presentation创建类型的对象'可选System.Boolean';因为'&LT(%)= WebApplication1.SiteHelper.IsUserInRole(管理)%>的可视

Cannot create an object of type 'System.Boolean' from its string representation '<%= WebApplication1.SiteHelper.IsUserInRole("Admin") %>' for the 'Visible'

推荐答案

类的一个有趣的问题。但作为错误消息状态,字符串&LT;%= WebApplication1.SiteHelper.IsUserInRole(管理员)%&GT; 无法转换为布尔

Kind of an interesting issue.. But as the error message states, the string <%= WebApplication1.SiteHelper.IsUserInRole("Admin") %> cannot be converted to a boolean.

不幸的是我无法解释为什么前pression不评估,而是被视为一个字符串。

Unfortunately i cannot explain why the expression isn't evaluated, but instead is treated like a string.

之所以你的&LT;%#%&GT; EX pression按预期工作,是因为它被视为大大不同。当页面被编译成类,那么编译器创建类似于这样的事件处理程序:

The reason why your <%# %> expression works as expected, is because it is treated much differently. When the Page is compiled into a class, then the compiler creates an event handler similar to this:

public void __DataBindingButton2(object sender, EventArgs e)
{
    Button button = (Button) sender;
    Page bindingContainer = (Page) button.BindingContainer;
    button.Visible = HttpContext.Current.User.IsInRole("admin");
}

和挂钩这种方法达到您的控制Control.Databinding事​​件。正如你所看到的,&LT;%#%&GT; 正在这个时候适当地视为服务器code,而不只是一个随机字符串

and hooks this method up to the Control.Databinding event on your control. As you can see, the <%# %> is this time properly treated as server code, and not just a random string.

所以我猜的解决方法是使用数据绑定,或去codebehind为AndreasKnudsen建议。

So i guess the solution is either to use databinding, or go to the codebehind as AndreasKnudsen suggests.

这篇关于分配按钮的Visible属性为一个静态方法结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆