SqlDataSource set SelectCommand dynamically

人走茶凉 提交于 2019-12-11 14:30:06

问题


I'm using a SqlDataSource and to avoid writing long queries directly in my code I thought I could make a Query class that returns the query I want as a string. I tried the code below but I just get "Server tags cannot contain <% ... %> constructs."

Before I was using stored procedures but my webhosting doesn't allow that, so thats when I thought about the Query class solution. I also need to add that I don't want to do databinding in codebehind.

Is there a way of doing this?

    <asp:SqlDataSource ID="DS" 
        runat="server"
        DataSourceMode="DataSet"  
        ConnectionString="<%$ ConnectionStrings:conn %>"
        ProviderName="MySql.Data.MySqlClient"
        SelectCommand="<% Query.getTestQuery() %>"
        >
    </asp:SqlDataSource>

回答1:


It is not possible to do this in ASP.NET. Code in <% %> tags is for running arbitrary code, not for setting property values. Code in <%= %> tags is for rendering to the output stream. Code in <%# %> is for databinding, which is similar to what you're trying to accomplish, but it's not the same. Code in <%$ %> is for expression bindings, but they execute too early in the page's life cycle and are thus unlikely to work in your scenario.

Using ObjectDataSource is one way to go here since at that point it's just code, and your code can do whatever it wants based on the state of the page.

Using a derived SqlDataSource is another option. Create a control that derives from SqlDataSource and override its OnInit method. In the OnInit method you can dynamically set the SelectCommand to do whatever you want based on the state of the page.




回答2:


Perhaps use an ObjectDataSource. That way, inside your object, you'll be able to do your dynamic query there.

Otherwise, you could modify the SelectCommand during the SqlDataSource Selecting Event in your code-behind. Then you could change the SelectCommand to whatever you like.



来源:https://stackoverflow.com/questions/1193256/sqldatasource-set-selectcommand-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!