[英]Setting imageURL using a function in ASP.NET
我之前在轉發器中完成了這個任務並且它已經工作了。 但是,我無法通過正常的webforms頁面獲得以下內容。 圖像顯示為斷開的鏈接,我在代碼隱藏中的斷點不會被觸發。
(在aspx文件中)
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# GetImageDirectory()%>btnRunReport.png' />
(代碼隱藏)
public string GetImageDirectory()
{
return "~/App_Variants/LBSX/images/";
}
這是我嘗試的第二種方法,在另一種方法中,我嘗試將imagename作為字符串傳遞,並且它會以這種方式返回整個鏈接。 仍然沒有運氣!
有什么想法嗎?
謝謝!
[編輯]感謝大家的幫助。 最后,在方便的提示后,我找到了一個遞歸片段,其功能如下:
private void UpdateImages(Control Parent)
{
foreach (Control c in Parent.Controls)
{
ImageButton i = c as ImageButton;
if (i != null)
{
i.ImageUrl = "~/App_Variants/LBSX/images/" + i.ImageUrl;
}
if (c.HasControls())
{
UpdateImages(c);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
UpdateImages(Page);
...
希望它可以幫助別人。
干杯
首先,就像Zachary提到的那樣,您正在使用代碼塊進行數據綁定。
其次,正如您已經嘗試過的那樣,使用內聯表達式( <%= %>
)在您的情況下也不會起作用,因為您不能對服務器標記的任何屬性使用內聯表達式。
您可以做的是使用HTML語法定義圖像按鈕,省略runat="server"
標記,並使用內聯表達式來獲取圖像的URL:
<input type="image" src="<%= GetImageDirectory() %>btnRunReport.png" name="image" />
內聯表達式的作用是,它使用<%= %>
之間的值作為參數調用Response.Write()
,例如<%= this.MyVar %>
是Response.Write(this.MyVar)
。
您的語法用於數據綁定,<%#%>。 如果您只是嘗試使用內聯c#,則應使用<%=%>。
我給你另一種解決方案。 使用ExpressionBuilder :
創建一個從ExpressionBuilder開始的類並覆蓋函數GetCodeExpression
namespace your.namespace { public class CustomBuilder : ExpressionBuilder { public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) { Type type1 = entry.DeclaringType; PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(type1)[entry.PropertyInfo.Name]; CodeExpression[] expressionArray1 = new CodeExpression[1]; expressionArray1[0] = new CodePrimitiveExpression(entry.Expression.Trim()); String temp = entry.Expression; return new CodeCastExpression(descriptor1.PropertyType, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(base.GetType()), "GenerateLink", expressionArray1)); } public static String GenerateLink(String link) { return ConfigurationManager.AppSettings["MediaPath"] + link + "?ver=" + ConfigurationManager.AppSettings["MediaCode"]; } } }
expressionArray1
是GenerateLink
函數的輸入數組。 您可以根據函數的輸入參數數量更改數組的大小
2.在webconfig中注冊表達式
<system.web>
<compilation debug="true" targetFramework="4.0" >
<expressionBuilders>
<add expressionPrefix="GenLink" type="your.namespace.CustomBuilder"/>
</expressionBuilders>
</compilation>
3.在視圖中你可以使用新的表達式:
<asp:ImageButton ID="ImageButton1" runat="Server" ImageUrl='<%$ GenLink:images/magnifier.jpg %>'/>
4.享受!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.