1

好的,这会很奇怪,但我的上一个项目都是 ASP.NET MVC 3、WCF/REST/SOAP 和 Win Forms 和 WPF。

我知道 HTTP 是无状态的,我开始对 Web Forms 在幕后关于 Web 控件所做的 VooDoo 感到奇怪。我真的在努力将我的思想包裹在 DataBinding 上。显然,它与 Win Forms DataBinding 技术有很大不同。

是否有任何好的模式和示例可以解释有关 DataBinding 和 Web 控件的实际情况?当我为 Win Forms 编程时,我似乎一直将其视为不断绑定到某些数据源。

4

2 回答 2

3

您应该了解的第一件事是ASP.NET 页面生命周期。一旦您了解了这一点,您将开始了解 Web 表单的机制。它可能看起来很神奇,因为它已经融入了架构,但是一旦你理解了它就真的很简单。

ASP.NET 和 WinForms 中的数据绑定存在很多差异,但基本概念仍然适用。了解数据绑定的最简单方法是查看数据绑定服务器控件的源。

以下是幕后发生的事情:

/// <summary>
/// Binds the data source to the control.
/// </summary>
public override void DataBind()
{
    this.PerformSelect();
}

/// <summary>
/// Retrieves data from the associated data source.
/// </summary>
protected override void PerformSelect()
{  
    //if the control is bound from a datasource control then
    //fire the ondatabinding event
    if (!this.IsBoundUsingDataSourceID)
        this.OnDataBinding(EventArgs.Empty);

    //retrive the data source view object and bind the data to the control
    this.GetData().Select(CreateDataSourceSelectArguments(), PerformDataBinding);

    //mark that the control has been bound to the source
    this.RequiresDataBinding = false;
    this.MarkAsDataBound();

    //fire the on data bound event so it can be 
    //handled from the parent object
    this.OnDataBound(EventArgs.Empty);
}

/// <summary>
/// Binds data from the data source to the control.
/// </summary>
/// <param name="retrievedData"></param>
protected override void PerformDataBinding(IEnumerable retrievedData)
{
    //call the base method
    base.PerformDataBinding(retrievedData);

    //clear all controls and viewstate data and reset
    //the viewstate tracking mechanism
    this.Controls.Clear();
    this.ClearChildViewState();
    this.TrackViewState();

    //generate all child controls within the hierarchy
    this.CreateControlHierarchy(true, retrievedData);

    //mark child controls created as true
    this.ChildControlsCreated = true;            
}

由于控件负责处理所有繁重的工作,因此在前端绑定数据非常容易;只需设置DataSource并调用DataBind()上面示例中的方法:

//assign the datasource to the control
GridView1.DataSource = new DataTable("DataSource"); 

//bind the datasource to the control
GridView1.DataBind(); 
于 2012-04-11T17:33:54.017 回答
0

看看4guysfromrolla。从记忆中,那里的文章非常全面。

于 2012-04-11T17:16:39.740 回答