Click here to Skip to main content
15,883,883 members
Articles / Web Development
Tip/Trick

Model Binder for ASP.NET Web Forms

Rate me:
Please Sign up or sign in to vote.
4.80/5 (4 votes)
11 Dec 2011CPOL 20.6K   9   2
Model Binder for ASP.NET Web Forms
Model Binder for ASP.NET Web Forms

Bind models to ASP.NET web form controls!

Download the source code and demo in Codeplex:
http://webformsmodelbinder.codeplex.com/

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:


C#
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:

C#
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.

XML
// 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):

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


Check out the detailed information in CodePlex!

Please share if you find this project useful. Thanks!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) JLT Interactive Pte Ltd
Singapore Singapore
Handy Torres is a .NET developer from the Philippines currently living in Singapore and working for JLT Interactive Private Limited as Senior IT Consultant.

Comments and Discussions

 
GeneralIt is really an awesome tip...My best wishes for your tip/tr... Pin
Balakrishnan Dhinakaran8-Dec-11 18:36
professionalBalakrishnan Dhinakaran8-Dec-11 18:36 
GeneralRe: Thanks! Pin
Handy Torres8-Dec-11 18:59
Handy Torres8-Dec-11 18:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.