适用于 ASP.NET Web Forms 的模型绑定器






4.80/5 (4投票s)
适用于 ASP.NET Web Forms 的模型绑定器
适用于 ASP.NET Web Forms 的模型绑定器 将模型绑定到 ASP.NET Web Forms 控件! 在 Codeplex 下载源代码和演示: http://webformsmodelbinder.codeplex.com/ 特性 (发布版 1)
- 双向模型绑定(将模型值绑定到控件,反之亦然)
- 支持集合类型
- 支持复杂类型(嵌套)
- 支持原生 ASP.NET 服务器控件和第三方控件(Telerik、Infragistics 等)
this.FirstName.Text = employee.FirstName; this.LastName.Text = employee.LastName; this.DateOfBirth.Text = employee.DateOfBirth.ToString();使用 ModelBinder 将模型绑定到页面控件(页面或用户控件)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Retrieve employee details from the database.
var employee = GetEmployeeFromDb();
// Bind the model to page controls.
ModelBinder.BindControl(employee, this);
}
}
将控件值绑定到模型
protected void SubmitClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Bind the control values to model.
var employee = ModelBinder.BindModel<Employee>(this);
// Do something like:
// EmployeeService.UpdateEmployee(employee);
}
}
下一步 (发布版 2) 绑定到数据源:使用 DataSource 特性将属性绑定到列表控件的 DataSource 属性。// Bind to a dropdownlist, checkboxlist, radiobuttonlist
// or 3rd party list control (e.g. Telerik's RadListBox, RadComboBox, etc.)
[MapToControl("Skills")]
[DataSource(DataTextField = "Description", DataValueField = "SkillId")]
public Collection<Skill> SkillList { get; set; }
// Add a default label with value.
[MapToControl("Skills")]
[DataSource(....., Label = "Please select...", LabelValue="0")]
public Collection<Skill> SkillList { get; set; }
// Add a default label from a resource file.
[MapToControl("Skills")]
[DataSource(....., LabelResourceName = "SelectLabel", LabelResourceType = typeof (Messages), LabelValue="0")]
public Collection<Skill> SkillList { get; set; }
模型验证(Required 和 Range 特性,以及 ModelErrors)[Required] public int? Age { get; set; } [Required(ErrorMessage = "Age is required")] public int? Age { get; set; } [Required(ErrorMessageResourceName = "AgeRequiredError", ErrorMessageResourceType = typeof (Messages))] public int? Age { get; set; } [Range(1, 60)] public int? Age { get; set; }检查模型是否有效并读取错误集合(PropertyName 和 ErrorMessage)
protected void SubmitClick(object sender, EventArgs e)
{
// Bind the control values to model.
var employee = ModelBinder.BindModel<Employee>(this);
if (ModelBinder.IsValid(employee))
{
// Do something like:
// EmployeeService.UpdateEmployee(employee);
}
else
{
// Do something with the model errors:
DispayTheErrorsInUI(employee.ModelErrors);
}
}
在 CodePlex 上查看详细信息! 如果您觉得这个项目有用,请分享。 谢谢!