2010-01-26 4 views
2

Existe-t-il un contrôle de source de données simplifié qui autoriserait la liaison à une méthode de page locale (code behind)? Un moyen d'accomplir ceci avec un ODS?Contrôle de source de données d'objet simplifié

L'ODS requiert le paramètre TypeName que je ne peux pas comprendre pour pointer vers la page locale (code derrière) dans un projet de site Web.

<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; } 
    } 

Répondre

1

Pas entièrement testé mais cela ne fonctionne pas. Je dois tester avec UserControls et MasterPages. Alors, oui, il peut être fait:

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; 
    } 
} 

Markup sur la page:

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

code sur la page:

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; } 
} 
1

Vous ne pouvez pas faire cela avec un contrôle ObjectDataSource. Vous pouvez le faire dans le code derrière, en définissant la propriété DataSource du DropDownList à votre objet et en appelant DataBind().

Questions connexes