代码之家  ›  专栏  ›  技术社区  ›  Sam Axe

如何将SqlDataSource ConnectionString属性绑定到函数

  •  3
  • Sam Axe  · 技术社区  · 16 年前

    我正在尝试将ConnectionString属性设置为aspx页中函数的返回值。

    例子:

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

    显然,上述措施不会奏效。所以…会怎样?

    先发制人的意见: *不,我不能使用web.config绑定

    3 回复  |  直到 11 年前
        1
  •  4
  •   Brian Webster Jason    12 年前

    您应该能够在页面加载中设置它,比如:

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

    或者,如果您不能访问代码隐藏,请在页面上放置一些内联代码,就像在sqldatasource的标记之前一样。

    <%
         blah.ConnectionString = ServerSensing.GetConnectionStringByServer("someKey");
    %>
    
        2
  •  1
  •   user150079    15 年前

    关于这个问题,我找到的最好方法是在解决方案中使用表达式生成器。

    使用此功能,您可以创建自定义内联表达式并在sqldatasource标记中使用它。

    Yuo会在这里找到一些例子:

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

    这就是我在应用程序中实现的方式:


    [ExpressionPrefix("RepConnectionString")]
    

    公共类repConnectionStringExpressionBuilder:ExpressionBuilder { 公共重写codeExpression getcodeExpression(boundPropertiesEntry项、对象ParsedData、ExpressionBuilderContext上下文) { codetypereferenceexpression thistype=新的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>      
    

        3
  •  0
  •   Joel Coehoorn    16 年前

    你能在代码后面设置连接字符串吗?