我正在使用ListView + DataPager + ObjectDataSource组合.
在我对ObjectDataSource的SelectMethod的实现中,我想访问PageLoad()事件中设置的全局变量(该方法每页只返回适当数量的项).尽管变量在PageLoad()中初始化,但在SelectMethod中似乎为null.我怎么能改变呢?
<asp:ObjectDataSource ID="ItemsObjectDataSource" runat="server" EnablePaging="True"
SelectMethod="WrapSearchResults" SelectCountMethod="CountSearchResults"
TypeName="Catalogue">
<SelectParameters>
<asp:QueryStringParameter Name="startRowIndex" QueryStringField="page" Type="Int32" DefaultValue="0" />
<asp:Parameter Name="maximumRows" Type="Int32" DefaultValue="10" />
</SelectParameters>
</asp:ObjectDataSource>
Run Code Online (Sandbox Code Playgroud)
SearchOption search;
protected void Page_Load(object sender, EventArgs e)
{
search = new SearchOption(SessionParameters.Get(Session).User);
}
public IEnumerable<ResultWrapper> WrapSearchResults(int startRowIndex, int maximumRows)
{
search.Limit = maximumRows; <-- null pointer exception
}
Run Code Online (Sandbox Code Playgroud)
这是对象数据源的常见问题.你总是要记住这个:
ODS将通过Reflection调用指定的方法,而不是对象的特定实例. (除非您指定要自己使用的实例)
该值为null,因为ODS直接调用了该方法,并且它从未成为asp.net页面生命周期的一部分.
如果您确实需要这样做,请将全局变量设置为STATIC.
protected **static** SearchOption search;
Run Code Online (Sandbox Code Playgroud)
如果您查看堆栈跟踪,就在null异常之前,您应该看到框架反射调用.这应该会让你知道发生了什么!
这是MSDN参考:
http://msdn.microsoft.com/en-us/library/ms227436.aspx
The ObjectDataSource control will create an instance of the source object, call the specified method, and dispose of the object instance all within the scope of a single request, if your object has instance methods instead of static methods (Shared in Visual Basic). Therefore, your object must be stateless. That is, your object should acquire and release all required resources within the span of a single request.
You can control how the source object is created by handling the ObjectCreating event of the ObjectDataSource control. You can create an instance of the source object, and then set the ObjectInstance property of the ObjectDataSourceEventArgs class to that instance. The ObjectDataSource control will use the instance that is created in the ObjectCreating event instead of creating an instance on its own.
小智 7
我有同样的问题,但我找到了解决方案.
或者您可以在VB代码中处理follow事件
Protected Sub PagingDataSource_ObjectCreating(ByVal sender As Object, ByVal e As ObjectDataSourceEventArgs) Handles PagingDataSource.ObjectCreating
e.ObjectInstance = Me
End Sub
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您将定义您的类的当前实例和整个变量.这是我自己测试的工作.还要为ODS定义metod的名称
<asp:ObjectDataSource ID="PagingDataSource" OnObjectCreating="PagingDataSource_ObjectCreating"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2853 次 |
| 最近记录: |