我正在尝试将ConnectionString属性设置为ASPX页面中函数的返回值。
示例:
<asp:SqlDataSource runat="server" id="blah"
ConnectionString="<%= ServerSensing.GetConnectionStringByServer("someKey"); %>"
>
...
</asp:SqlDataSource>
以上显然不会起作用..那么......会是什么?
先发制人的评论: *不,我不能使用Web.config绑定
答案 0 :(得分:4)
您应该可以在Page_Load中设置它,例如:
blah.ConnectionString = ServerSensing.GetConnectionStringByServer("someKey");
或者如果您无法访问后面的代码,请在页面上放置一些内联代码,就像在SqlDataSource的标记之前那样
<%
blah.ConnectionString = ServerSensing.GetConnectionStringByServer("someKey");
%>
答案 1 :(得分:1)
我发现这个问题的最好方法是在解决方案中使用Expression Builder。
使用此功能,您可以创建自定义内联表达式并在SqlDataSource标记中使用它。
Yuo会在这里找到一些例子:
http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
这就是我在我的应用中实现的方式:
[ExpressionPrefix("RepConnectionString")]
public class RepConnectionStringExpressionBuilder:ExpressionBuilder { public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,object parsedData,ExpressionBuilderContext context) { 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;
}
}
:
<compilation>
<expressionBuilders>
<add expressionPrefix="RepConnectionString" type="RepConnectionStringExpressionBuilder"/>
</expressionBuilders>
答案 2 :(得分:0)
您可以在后面的代码中设置连接字符串吗?