简化的对象数据源控制

时间:2010-01-26 22:23:03

标签: asp.net

是否有任何简化的数据源控件允许绑定到本地(代码隐藏)页面方法?有没有办法用ODS实现这个目标?

ODS需要TypeName参数,我无法指出它指向网站项目中的本地页面(代码隐藏)。

<asp:DropDownList ID="DropDownListMain" runat="server" DataTextField="Text" DataValueField="Value"
    DataSourceID="DataSourceMain" />
<asp:ObjectDataSource ID="DataSourceMain" runat="server" SelectMethod="GetMyRecords" />

   protected IEnumerable<MyRecord> GetMyRecords()
    {
        yield return new MyRecord("Red", "1");
        yield return new MyRecord("Blue", "2");
        yield return new MyRecord("Green", "3");
        yield return new MyRecord("Black", "4");
    }

    protected class MyRecord
    {
        public MyRecord(string text, string value)
        {
            this.Text = text;
            this.Value = value;
        }

        public string Text { get; set; }
        public string Value { get; set; }
    }

2 个答案:

答案 0 :(得分:1)

使用ObjectDataSource控件无法执行此操作。您可以在后面的代码中执行此操作,方法是将DataSource的{​​{1}}属性设置为您的对象并调用DropDownList

答案 1 :(得分:1)

尚未完全测试但这确实有效。我需要使用UserControls和MasterPages进行测试。所以,是的,可以做到:

public class LocalDataSource : LinqDataSource
{
    public LocalDataSource()
    {
        this.Selecting += (sender, e) =>
        {
            var instance = GetHost(this.Parent);

            e.Result = instance.GetType().InvokeMember(SelectMethod, BindingFlags.Default | BindingFlags.InvokeMethod, null, instance, null);
        };
    }

    public string SelectMethod
    {
        get { return (string)ViewState["SelectMethod"] ?? string.Empty; }
        set { ViewState["SelectMethod"] = value; }
    }

    private object GetHost(Control control)
    {
        if (control.Parent is System.Web.UI.Page)
            return control.Parent;

        if (control.Parent is System.Web.UI.UserControl)
            return control.Parent;

        if (control.Parent != null)
            return GetHost(control.Parent);

        return null;
    }
}

页面上的标记:

<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="Name" DataValueField="ID"
    DataSourceID="DataSource1" />
<ph:LocalDataSource id="DataSource1" runat="server" SelectMethod="GetNames" />

页面上的代码:

public IEnumerable<NameRecord> GetNames()
{
    yield return new NameRecord("Andy", "1");
    yield return new NameRecord("Chad", "2");
    yield return new NameRecord("Jayson", "3");
}

public class NameRecord
{
    public NameRecord(string name, string id)
    {
        this.Name = name;
        this.ID = id;
    }

    public string Name { get; set; }
    public string ID { get; set; }
}