与ObjectDataSource的摔跤 - 其他控件和变量没有定义 [英] Wrestling with ObjectDataSource - other controls and variables not defined

查看:165
本文介绍了与ObjectDataSource的摔跤 - 其他控件和变量没有定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GridView与一个ObjectDataSource,有点像这样的:

I have a Gridview with an ObjectDataSource, sort of like this:

<asp:GridView ID="myGridView" runat="server" AllowSorting="True" ondatabound="myGridView_DataBound" cssClass="coolTable" 
        OnRowDataBound="myGridView_RowDataBound"
         AllowPaging="True" AutoGenerateColumns="False" DataSourceID="myDataSource">
        <PagerSettings mode="NextPreviousFirstLast">
        </PagerSettings>
</asp:GridView>
<asp:ObjectDataSource ID="myDataSource" runat="server"  
         SelectMethod="GetSearchResults" EnablePaging="true"
         StartRowIndexParameterName="startIndex" 
         MaximumRowsParameterName="pageSize"
         SortParameterName="sortBy" SelectCountMethod="GetSearchCount" >   
</asp:ObjectDataSource>

安迪我的功能,GetSearchResults,叫,让一切都很好。的问题是,在GetSearchResults,我想使用其它变量除了传递给它的那些,但他们似乎并不GetSearchResults运行时具有的值。我在调试加强,并且我可以看到的Page_Load被GetSearchResults之前调用 - 但引用任何控件我的网页上抛出一个错误,而属于我的页字段没有价值(即使我将它们设置在Page_Load中)。

Andy my function, GetSearchResults, is called, so that's all good. The problem is that in GetSearchResults, I want to use other variables besides the ones passed to it, but they do not seem to have values when GetSearchResults runs. I stepped through in the debugger, and I can see that Page_Load is called before GetSearchResults - but referencing any of the controls on my page throws an error, and fields belonging to my page have no value (even though I set them at Page_Load).

我看了 ASP.Net对象的数据源 - 数据绑定和脱脂页生命周期概述挂在那里,但还是不明白,为什么我的其他变量是不可用的。

I read ASP.Net Object Data Source - Data Binding and skimmed the Page Life Cycle Overview linked to there, but still do not understand why my other variables are not available.

但这里是我的真正的问题 - 我真的不关心他们为什么是不可用;我想知道的良好格局,使我GetSearchResults功能可用值(即在Page_Load期间分别设置)。目前我节省了会议的事情,但似乎有点可笑了。

But here is my real question - I don't really care why they aren't available; I would like to know a good pattern to make values available (that were set during Page_Load) to my GetSearchResults function. Currently I'm saving things in session, but that seems kind of ridiculous.

【编辑添加背景]
我做对的Page_Load一些数据库查询来设置一些值这反过来又影响到我的页面布局和内容。这些值也被用于修改数据的选择标准在我的GridView。我开始使用ObjectDataSource,因为让我经历了很多的记录efficently页面( HTTPS ://msdn.microsoft.com/en-us/library/bb445504.aspx ),但最初并未明白页面的新实例被创建,之后调用的方法 - 我一直以为是像回传处理。我希望避免表单域,会话变量等,看起来也许这样做是正常的页面生命周期中,以填补在GridView的唯一办法节省的中间值,但它看起来像这意味着放弃自动分页的GridView控件。

I am doing some database queries on Page_Load to set some values which in turn affect the layout and content of my page. Those values are also used to modify the selection criteria for the data in my GridView. I started using the ObjectDataSource because to allow me to efficently page through a lot of records (https://msdn.microsoft.com/en-us/library/bb445504.aspx) but didn't initially understand that a new instance of the Page is created and the method called after that - I was thinking it was handled like a postback. I was hoping to avoid saving those interim values in form fields, session variables, etc. It looks like maybe the only way to do that is to fill the Gridview during the normal page lifecycle, but it looks like that means giving up the automatic paging of the Gridview.

推荐答案

当你开始使用ASP.NET的DataSourceControls(ObjectDataSource控件,SqlDataSource的,的AccessDataSource等)及其对应DataBoundControls(DropDownList中,DetailsView控件,ListView控件,FormView控件,GridView控件) ,你真的想了解ASP.NET生命周期忘了(并停止揪头发),如果你做得很好,你甚至可以忘记code-背后code(aspx.cs文件),因为现在系统可以pretty数据源和数据绑定控件之间自动完成的。

When you start using ASP.NET's DataSourceControls (ObjectDataSource, SqlDataSource, AccessDataSource, etc.) and their counterparts DataBoundControls (DropDownList, DetailsView, ListView, FormView, GridView), you really want to forget about ASP.NET lifecycle (and stop pulling hair), and if you do it well, you can even forget about code-behind code (aspx.cs files) because now the system can be pretty automatic between datasources and databound controls.

其实这种模式(即只出现开始.NET 2.0)确实有助于集中在声明类似HTML的code。

In fact this paradigm (that has appeared only starting with .NET 2.0) really helps to focus on declarative HTML-like code.

一个DataSourceControl使用类型的对象集合的参数作为参数,它使用的方法。例如,ObjectDataSource的SelectMethod使用<一个href=\"https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.selectparameters.aspx\"相对=nofollow> SelectParameters (的ParameterCollection中类型)。酒店

A DataSourceControl uses a collection of objects of type Parameter as parameters to the methods it uses. For example, the ObjectDataSource's SelectMethod uses the SelectParameters property (of ParameterCollection type).

您可以声明定义这些参数。让我们看一个例子:

You can define these parameters declaratively. Let's take an example:

<form id="form1" runat="server">
<div>
    <asp:TextBox ID="MyTextBox" Text="3" runat="server" />
    <asp:Button runat="server" Text="Run" />

    <asp:GridView ID="myGridView" runat="server" DataSourceID="myDataSource" />
    <asp:ObjectDataSource ID="myDataSource" runat="server" 
             SelectMethod="GetSearchResults"
             TypeName="WebApplication1.Code.MyModel">
        <SelectParameters>
            <asp:ControlParameter ControlID="MyTextBox" PropertyName="Text" Name="myCount" />
        </SelectParameters>
    </asp:ObjectDataSource>
</div>
</form>

在这里,myDataSource定义了一个 GetSearchResults SelectMethod (我忽略你的其他参数,但想法是在某些类为MyModel 类相同)的方法。它还定义了一个名为参数 mycount的。此参数是一个 ControlParameter (有有其他人):它会连接到ASP.NET控件 MyTextBox 这恰好被定义为一个文本框控件,将使用文本框的文本属性作为 mycount的参数的值。

Here, myDataSource defines a GetSearchResults as the SelectMethod (I've omitted your other parameters but the idea is the same) method on a MyModel class in some class. It also defines a parameter named myCount. This parameter is a ControlParameter (there are others): it will connect to the ASP.NET control MyTextBox which happens to be defined as a TextBox control, and will use the TextBox's Text property as the the value of the myCount parameter.

下面是对象模型的code:

Here is the code of the object model:

namespace WebApplication1.Code
{
    public class MyModel
    {
        public string Name { get; set; }

        public static IEnumerable GetSearchResults(int myCount)
        {
            for (int i = 0; i < myCount; i++)
            {
                yield return new MyModel { Name = "item " + i };
            }
        }
    }
}

如您所见,该方法还定义了 mycount的参数(这是区分大小写的,是的,ASP.NET将从自动转换成字符串 INT ,它几乎神奇的,它使用类型转换器引擎盖下),所以一切都将如预期,的没有任何code-背后code 的。这是某种形式的MV模式(M V型视图)和DataSourceControl / DataBoundControl做了绑定。

As you see, the method also has a myCount parameter defined (it's case sensitive, and yes, ASP.NET will convert automatically from string to int, it's almost magic, it uses TypeConverters under the hood), so everything will work as expected, without any code-behind code. It's some kind of an MV pattern (M model V view) and DataSourceControl/DataBoundControl do the binding.

所以,你必须有这样的想法,现在,使用参数。如果提供的参数(查询字符串,饼干,形式,​​档案,路线,会议)名单没有的话,你可以提供你自己的。例如,我可以定义一个特殊参数,将获得随机mycount的(这只是一个例子: - ):

So, you have to think this way now, and use parameters. If the provided list of parameters (QueryString, Cookie, Form, Profile, Route, Session) is no enough, you can provide your own. For example I can define a special parameter that will get myCount randomly (it's just an example :-):

我可以这样使用它,我可以自定义参数此参数:

I can use it like this, and I can define custom arguments for this parameter:

<%@ Register Namespace="WebApplication1.Code" TagPrefix="my" Assembly="WebApplication1" %>
...
<SelectParameters>
    <my:RandomParameter Name="myCount" Min="10" Max="20" />
</SelectParameters>

自定义参数类型code:

The custom parameter type code:

public class RandomParameter : Parameter
{
    protected override object Evaluate(HttpContext context, Control control)
    {
        // you can get to page or environment from here with 'context' and 'control' parameters
        return new Random(Environment.TickCount).Next(Min, Max);
    }

    [DefaultValue(1)]
    public int Min
    {
        get
        {
            object o = ViewState["Min"];
            return o is int ? (int)o : 1;
        }
        set
        {
            if (Min != value)
            {
                ViewState["Min"] = value;
                OnParameterChanged();
            }
        }
    }

    [DefaultValue(10)]
    public int Max
    {
        get
        {
            object o = ViewState["Max"];
            return o is int ? (int)o : 10;
        }
        set
        {
            if (Max != value)
            {
                ViewState["Max"] = value;
                OnParameterChanged();
            }
        }
    }
}

这篇关于与ObjectDataSource的摔跤 - 其他控件和变量没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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