2009-04-08 66 views
3

我試圖將ConnectionString屬性設置爲ASPX頁面中函數的返回值。我將如何將SqlDatasource連接字符串屬性綁定到函數

例子:

<asp:SqlDataSource runat="server" id="blah" 
    ConnectionString="<%= ServerSensing.GetConnectionStringByServer("someKey"); %>" 
    > 
    ... 
</asp:SqlDataSource> 

以上顯然行不通的..所以..什麼會?

搶先發言: *不,我不能使用的Web.config結合

+0

你沒有張貼任何例子 – hunter 2009-04-08 01:01:55

回答

4

你應該能夠將其設置在Page_Load中,是這樣的:

blah.ConnectionString = ServerSensing.GetConnectionStringByServer("someKey"); 

,或者如果你沒有訪問到後面的代碼放在網頁上的一些行內代碼,就像剛標記爲前SqlDataSource

<% 
    blah.ConnectionString = ServerSensing.GetConnectionStringByServer("someKey"); 
%> 
0

你可以設置連接字符串後面的代碼?

1

我發現有關此問題的最佳方式是在您的解決方案中使用表達式生成器。

使用此功能,您可以創建自定義內聯表達式並將其用於SqlDataSource標記中。

Yuo'll找到一些例子就在這裏:

http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx

這就是我在我的應用程序如何實現的:


[ExpressionPrefix("RepConnectionString")] 

公共類RepConnectionStringExpressionBuilder:的ExpressionBuilder { 公衆覆蓋CodeExpression GetCodeExpression(BoundPropertyEntry條目,對象parsedDat a,ExpressionBuilderContext上下文) { CodeTypeReferenceExpression thisType = new CodeTypeReferenceExpression(base.GetType());

CodePrimitiveExpression expression = new CodePrimitiveExpression(entry.Expression.Trim().ToString()); 

    string evaluationMethod = "GetConnectionString"; 

    return new CodeMethodInvokeExpression(thisType, evaluationMethod, new CodeExpression[] { expression }); 
} 


public static string GetConnectionString(string expression) 
{ 
    XmlDocument xmlDoc = new XmlDocument(); 
    string wPath = HttpContext.Current.Server.MapPath("~/XmlFile.xml"); 
    xmlDoc.Load(wPath); 
    XmlNode wNode = xmlDoc.SelectSingleNode("Autenticacoes/Database[@id='" + expression + "']"); 

    string wConnString = ""; 
    if (wNode != null) 
    { 
     wConnString = "Data Source=" + wNode.Attributes["servidor"].Value + ";Initial Catalog=" + wNode.Attributes["db"].Value + ";Persist Security Info=True;User ID=" + wNode.Attributes["login"].Value + ";Password=" + wNode.Attributes["senha"].Value; 
    } 

    return wConnString; 
} 

}


在web.config

<compilation> 
    <expressionBuilders> 
    <add expressionPrefix="RepConnectionString" type="RepConnectionStringExpressionBuilder"/> 
    </expressionBuilders>  

相關問題