0

我正在尝试在我的母版页中使用 AppSettings 显示 asp:ImageButton 的 ImageUrl,如下所示:

 View.Master:
 ....
 <asp:ImageButton ID="aspShowHideButton" ImageUrl='<%# System.Configuration.ConfigurationManager.AppSettings("HomeDirectory").ToString()%>images/arrowUpButton.gif' runat="server" />

不幸的是,当我在浏览器中提取它时,这是正在呈现的代码:

 <input type="image" name="ctl00$ctl00$aspContentMain$aspShowHideButton" id="aspContentMain_aspShowHideButton" onmouseover="ShowHideButtonMouseOver()" onmouseout="ShowHideButtonMouseOut()" src="../%3C%25#%20System.Configuration.ConfigurationManager.AppSettings(%22HomeDirectory%22).ToString()%25%3Eimages/arrowUpButton.gif" />

因此,它从字面上获取了我的 ImageUrl,但我希望它获取键的值,即:

  ...
  <appSettings>
        ....
        <add key="HomeDirectory" value="/" />
        ....

我试过了,删除了“ToString()”函数,我试过 System.Configuration.... 语句前面的“#”和“$”。我还尝试尝试让它在 Page_Load 函数中工作,使用:

 Protected Sub Page_Load(....)
    If Not IsNothing(Master.FindControl("aspShowHideButton")) Then
       Dim ShowHideButton As ImageButton = Master.FindControl("aspShowHideButton")
       ShowHideButton.ImageUrl = System.Configuration.ConfigurationManager.AppSettings("HomeDirectory") + "images/arrowUpButton.gif"
    End If

但这似乎也不起作用,我假设是因为它找不到我正在寻找的控件(即 aspShowHideButton)。

从根本上说,我希望在我的 web.config 文件中有一个键/值对,它允许我更改图像的位置,并且我希望能够在我的母版页上的 ImageButton:ImageUrl 中使用这个键/值对,这似乎是一件非常受欢迎的事情。任何建议,方向,不胜感激!

谢谢!

4

2 回答 2

2

要在服务器标签中使用 appsettings,请使用以下语法:

<%$ AppSettings:HomeDirectory %>

但是您将无法连接 ImageUrl 的后缀。请注意,如果您想在 asp.net 服务器控件中引用主目录, ~ 就可以了。

 <asp:ImageButton ID="aspShowHideButton" ImageUrl="~/images/arrowUpButton.gif" runat="server"/>

简单的解决方案

在服务器端代码上初始化 ImageUrl 属性,例如 Page_Load 事件。在那里,您将能够使用您想要的任何服务器代码。

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
       this.aspShowHideButton.ImageUrl = System.Configuration.ConfigurationManager.AppSettings("HomeDirectory").ToString() + "images/arrowUpButton.gif";
    }
}

现在,如果您确实需要直接在 ImageButton 标记中定义这种连接,您将需要使用代码表达式生成器。在这里阅读

使用 Code Expression Builder,您将能够在 ImageButton 标记中使用这种语法:

ImageUrl="<%$ Code: System.Configuration.ConfigurationManager.AppSettings("HomeDirectory").ToString() + "images/arrowUpButton.gif" %>"
于 2012-04-11T19:04:42.413 回答
1

你可以试试这个:

<asp:ImageButton runat="server" ImageUrl="<%$ AppSettings:FullPath %>images/image001.jpg" ></asp:ImageButton>

(或者)有一个小工作可以解决这个问题:

网络配置:

<appSettings> 
<add key="testKey" value="images/up.gif" />
</appSettings>  

添加图片按钮:

<asp:ImageButton ID="ImageButton1" runat="server" />

从代码隐藏你可以这样调用:

 protected void Page_Load(object sender, EventArgs e)
    {
        this.ImageButton1.ImageUrl = ConfigurationManager.AppSettings["testKey"];
    }
于 2012-04-11T19:08:23.650 回答