Simplified Object Data Source Control
Is there any simplified Data Source Control that would allow binding to a local (code behind) page method? Any way to accomplish this with an ODS?
The ODS requires the TypeName parameter which I can't figure out to to point to the local page (code behind) in a Web Site Project.
<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; }
}
You can't do this with an ObjectDataSource
control. You can do it in the code behind though, by setting the DataSource
property of the DropDownList
to your object and calling DataBind()
.
Not fully tested but this does work. I need to test with UserControls and MasterPages. So, yes, it can be done:
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 on the page:
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="Name" DataValueField="ID"
DataSourceID="DataSource1" />
<ph:LocalDataSource id="DataSource1" runat="server" SelectMethod="GetNames" />
Code on the 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; }
}
精彩评论