双向数据绑定在ASP.NET [英] Two way databinding in ASP.NET

查看:195
本文介绍了双向数据绑定在ASP.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让说,我们有一个对象

class Entity
{
    public string ID {get; set;}
    public string Name {get; set;}
}

我想在一个页面像这样绑定属性,两个文本框:

i want to bind properties to two textboxes on a page something like this:

<asp:FormView ID="FormView" runat="server">
  <ItemTemplate>
    <asp:textbox ID="TextId" Text='<%# Bind("ID") %>'/>
    <asp:textbox ID="TextId" Text='<%# Bind("Name") %>'/>
  </ItemTemplate>
</asp:FormView>

,然后写在code后面

and then write this in code behind

public EntityObject
        {
            get { return ViewState["Entity"] as Entity; }
            set { ViewState["Entity"] = value; }
        }
protected override void OnInit(EventArgs e)
        {
            if (EntityObject== null)
                EntityObject= new EntityObject();

            FormView.DataSource = new[] { EntityObject };
            FormView.DataBind();
            base.OnInit(e);
        }

当我在文本框中输入值,我希望EntityObject有这些值的属性时回传后页面重新加载,但性能总是空。请帮帮忙,我要去哪里错了?

And when i enter values in textboxes i expect EntityObject to have these values in properties when page reloads after PostBack, but properties are always null. Please help, where i'm going wrong?

推荐答案

黯然地说,但aps.net不支持双向绑定到.NET对象... 相反,您可以使用类似手工绑定在每一个岗位回(这里AddIncomeSources是RepeaterControl)

sadly to say that, but aps.net does not support two-way binding to .net objects... instead you can use something like "manual binding" on every post back (here AddIncomeSources is RepeaterControl)

        public List<Income> AdditionalIncomeList 
        {
            get { return ViewState["AdditionalIncome"] as List<Income>; }
            set { ViewState["AdditionalIncome"] = value; }
        }                
            foreach (RepeaterItem item in AddIncomeSources.Items)
            {
                var amount = (TextBox)item.Controls.Cast<Control>().First(c => c.ID == "Amount");
                var document = (DropDownList)item.Controls.Cast<Control>().First(c => c.ID == "Document");
                AdditionalIncomeList[item.ItemIndex].Amount = amount.Text.ToDouble();
                AdditionalIncomeList[item.ItemIndex].IncomeDocument = document.SelectedValue;
            }
            AddIncomeSources.DataSource = AdditionalIncomeList;
            AddIncomeSources.DataBind();

这篇关于双向数据绑定在ASP.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆