views:

754

answers:

3

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>
A: 

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.

davewasthere
A: 

So there is no way to do it the way I thought? As I said I don't want to databind in codebehind. Thanks for your help!

Tip: If something is difficult to achieve in ASP.NET your approach to it is probably flawed.
Dan Diplo
Yes I understand, I was using stored procedures but as my webhost doesn't allow that I need to find nother way.
+1  A: 

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.

Eilon