什么是ObjectDataSource的重点

时间:2011-09-30 02:37:07

标签: asp.net data-binding ienumerable objectdatasource

鉴于每个网格,组合框,checkboxlist和一般多行控件都支持直接绑定到任何IEnumerable,ObjectDataSource的重点是什么?

为什么会使用它而不是直接绑定到您的收藏?特别是如果您已经在业务,演示文稿和数据层中合理地分离了关注点?

自从引入LINQ以来,我也觉得这是一个更为相关的问题。我经常发现,在绑定时我想使用LINQ执行一些进一步的排序,排除等等,我相信在使用ObjectDataSource而不为您创建特定方法(可能是单个用例)时这是不可能的吗?

那么什么时候使用ObjectDataSource是合适的?与直接绑定到IEnumerable相比有哪些优势?

2 个答案:

答案 0 :(得分:4)

首先,ObjectDataSource通常用于ASP.NET WebForms(aspx)。 ObjectDataSource位于System.Web.UI.WebControls中,因为您可以在MSDN Library上看到此链接:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.aspx

使用ObjectDataSource绑定数据意味着绑定您将数据源作为对象,可以采用DataSet的形式或任何其他实现IEnumerable的.NET对象。使用ObjectDataSource意味着您必须执行通常在SqlDataSource中找到的自己的Select,Update,Insert和Delete方法。

MSDN Library中有一个很好的演练:Walkthrough: Data Binding to a Custom Business Object

但是在没有实现IListSource的情况下绑定到简单的IEnumerable(就像DataTable一样)意味着你将没有很好的功能,例如对GridView等复杂数据控件的数据绑定。而且你也会失去其他功能,因为单独的IEnumerable不能以两种方式绑定到其他列表控件,如ListView和GridView。

为了使您的数据可以双向绑定,您的对象在将IListSource作为数据项添加到IListSource之前还必须实现INotifyPropertyChanged接口。

样品:

public class Employee : BusinessObjectBase
{
    private string      _id;
    private string      _name;
    private Decimal     parkingId;

    public Employee() : this(string.Empty, 0) {}
    public Employee(string name) : this(name, 0) {}

    public Employee(string name, Decimal parkingId) : base()
    {
        this._id = System.Guid.NewGuid().ToString();

        // Set values
        this.Name = name;
        this.ParkingID = parkingId;
    }

    public string ID
    {
        get { return _id; }
    }

    const string NAME = "Name";
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;

                // Raise the PropertyChanged event.
                OnPropertyChanged(NAME);
            }
        }
    }

    const string PARKING_ID = "Salary";
    public Decimal ParkingID
    {
        get { return parkingId; }
        set
        {
            if (parkingId != value)
            {
                parkingId = value;

                // Raise the PropertyChanged event.
                OnPropertyChanged(PARKING_ID);
            }
        }
    }
}

这是INotifyPropertyChanged:

的实现
public class BusinessObjectBase : INotifyPropertyChanged
{
    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
    }

    private void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (null != PropertyChanged)
        {
            PropertyChanged(this, e);
        }
    }

    #endregion
}

答案 1 :(得分:0)

如果你不想要代码隐藏,你可以用它绑定枚举。