一个简单的Spring.net绑定例子
下午的时候碰到一个需求,同事需要根据数据库里的表,自动在Aspx Page上添加相应的TextBox控件,并将值绑定到TextBox文本框上,同样的,在保存时也希望能保存回数据库。
为了支持双向绑定,用Spring.net的Spring.DataBinding.BaseBindingManager来做是个简单的方法,碰到的问题是:Spring.net的绑定表达式是基于属性的,而动态加入的txtName, txtAge是无法通过"Page.txtName", "Page.txtAge"来访问的,即我们动态加入的控件被放到了Page.Form.Controls里了。
解决的办法很简单,为页面加入this["name"]方式的属性访问器:
public Control this[string name]
{
get { return this.FindControl(name); }
}
在绑定表达式只要这样写即可:['name'].Text ,由此把动态加入的控件看着Page的this["name"]属性。
完整的例子代码如下:
为了支持双向绑定,用Spring.net的Spring.DataBinding.BaseBindingManager来做是个简单的方法,碰到的问题是:Spring.net的绑定表达式是基于属性的,而动态加入的txtName, txtAge是无法通过"Page.txtName", "Page.txtAge"来访问的,即我们动态加入的控件被放到了Page.Form.Controls里了。
解决的办法很简单,为页面加入this["name"]方式的属性访问器:
public Control this[string name]
{
get { return this.FindControl(name); }
}
在绑定表达式只要这样写即可:['name'].Text ,由此把动态加入的控件看着Page的this["name"]属性。
完整的例子代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Spring.DataBinding;
public class People
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public partial class PollutionManage_Spring : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BaseBindingManager manager = new BaseBindingManager();
TextBox box = new TextBox();
box.Text = "hello";
box.ID = "hi";
this.Form.Controls.Add(box);
People p = new People();
p.Name = "jiyang";
manager.AddBinding("Name", "['hi'].Text");
manager.BindSourceToTarget(p, this, null);
}
}
public Control this[string name]
{
get { return this.FindControl(name); }
}
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Spring.DataBinding;
public class People
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public partial class PollutionManage_Spring : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BaseBindingManager manager = new BaseBindingManager();
TextBox box = new TextBox();
box.Text = "hello";
box.ID = "hi";
this.Form.Controls.Add(box);
People p = new People();
p.Name = "jiyang";
manager.AddBinding("Name", "['hi'].Text");
manager.BindSourceToTarget(p, this, null);
}
}
public Control this[string name]
{
get { return this.FindControl(name); }
}
}