SIGN UP MEMBER LOGIN:    
ARTICLE

Model Binder for ASP.NET Web Forms

Posted by Handy Torres Articles | ASP.NET Programming December 13, 2011
Here I will demonstrate the Model Binder for ASP.NET Web Forms.
Reader Level:
Download Files:
 

Bind models to ASP.NET web form controls!

Features (Release 1)

  • Two-way model binding (bind model values to controls and vice versa)
  • Supports collection types
  • Supports complex types (nested)
  • Supports native ASP.NET server controls and 3rd party controls (Telerik, Infragistics, etc.)

See the What's next section for release 2 features.

Instead of manually binding properties to web forms like this:

this.FirstName.Text = employee.FirstName;
this.LastName.Text = employee.LastName;
this.DateOfBirth.Text = employee.DateOfBirth.ToString();

Bind the model to page controls (Page or User Control) using the 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);}
}


Bind the control values to the model:

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);
    }
}

What's Next (Release 2)

Bind to datasource: Use the DataSource attribute to bind a property to a list control's datasource property.

// 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; }

Model validation (Required and Range attributes, and 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; }

Check if the model is valid and read the errors collection (PropertyName and 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);
     }
}

Please share if you find this project useful. Thanks!
 

Login to add your contents and source code to this article
share this article :
post comment
 

Hi handy you have done good work.......Thanks for sharing.....

Posted by Vikas Mishra Dec 14, 2011

My sincere apologies for the garbled release 2 section. Having a hard time with the editor...

Posted by Handy Torres Dec 14, 2011

Thanks guys, i will be releasing v2 soon. For more information, please checkout: webformsmodelbinder.codeplex.com Please share if you think it's useful. Cheers!

Posted by Handy Torres Dec 14, 2011

Good Article, Handy. Thanks for sharing your thought.

Posted by Alok Pandey Dec 14, 2011

Good Job Handy... :)

Posted by Sonakshi Singh Dec 14, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor