SqlDataSource动态设置SelectCommand [英] SqlDataSource set SelectCommand dynamically

查看:54
本文介绍了SqlDataSource动态设置SelectCommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是SqlDataSource,为避免直接在代码中编写长查询,我认为我可以创建一个Query类,该查询类以字符串形式返回我想要的查询.我尝试了下面的代码,但只得到服务器标记不能包含<%...%>构造".

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."

在我使用存储过程之前,但我的虚拟主机不允许这样做,所以这就是我想到Query类解决方案的时候.我还需要补充一点,我不想在代码隐藏中进行数据绑定.

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>

推荐答案

在ASP.NET中无法执行此操作.<%%> 标记中的代码用于运行任意代码,而不用于设置属性值.<%=%> 标记中的代码用于呈现到输出流.<%#%> 中的代码用于数据绑定,这与您要实现的功能相似,但并不相同.<%$%> 中的代码用于表达式绑定,但是它们在页面生命周期中执行得太早,因此不太可能在您的情况下起作用.

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.

使用ObjectDataSource是到达此处的一种方法,因为此时它只是代码,并且您的代码可以根据页面的状态执行所需的任何操作.

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.

使用派生的SqlDataSource是另一种选择.创建一个从SqlDataSource派生的控件,并覆盖其 OnInit 方法.在 OnInit 方法中,您可以根据页面状态动态设置SelectCommand以执行所需的任何操作.

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.

这篇关于SqlDataSource动态设置SelectCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆