2009-04-08 30 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>  

相关问题