【问题标题】:Learning ASP.NET Webforms with an MVC and Win Forms Background用 MVC 和 Win Forms 背景学习 ASP.NET Webforms
【发布时间】:2012-04-12 09:57:17
【问题描述】:

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

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

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

【问题讨论】:

标签: asp.net webforms


【解决方案1】:

您应该了解的第一件事是ASP.NET Page Life Cycle。一旦您了解了这一点,您将开始了解 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(); 

【讨论】:

  • 我认为这是我应该走的路。我对来自客户端和 mvc 端编程的 Web 表单的异教方式感到非常困惑。我想知道是否有一个具有良好模式和实践的好网站可以帮助我进一步理解它。
【解决方案2】:

看看4guysfromrolla。凭记忆,那里的文章相当全面。

【讨论】:

    猜你喜欢
    • 2011-01-15
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    相关资源
    最近更新 更多