Monday 21 September 2009

Controlling data binding with ASP.Net MVC

If you use the UpdateModel() Controller helper method to bind data you can enforce which properties are bound to prevent unwanted data manipulation. There are three methods you can employ to provide MVC with an inclusion list of the properties to be bound.

Pass in an array of strings containing the names of the properties to be bound.

string[] properties = new[]{"Property1", "Property2"}; 
UpdateModel(myModel, properties);

Add a bind attribute to the controller action.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction( [Bind(Include="Property1, Property2")] MyModelType model ) { //... }

Add a bind attribute to your model type. Note that this can be either an inclusion or exclusion list.

[Bind(Include="Property1, Property2")] 
public partial class MyModelType { //... }