Monday, November 30, 2009

Mapping URLs using ASP.NET 2.0 Web Forms

ASP.NET 4.0 is coming with new feature - URL routing with ASP.NET Web Forms

It is pretty cool feature, but require upgrade up to .NET 4.0.
I am not sure that such a good feature is a real reason to get upgraded, and in most cases you will stay with current version on .NET.

But I want it and I want it now, with .NET 3.5. I am going to implement it!

Tuesday, November 24, 2009

ASP.NET MVC Model Binding and Model's fields

A Model Binding in MVC provides a simple way to map posted form values to a .NET Framework type and pass the type to an action method as a parameter.

Everything works fine while a model has public properties like this:

public Person
public string Id {get;set;}
public string Name {get;set;}

But if you try to use public fields instead of properties like this:

public Person
public string Id;
public string Name;

you will be surprised to get the model passed to controller's action with no assigned fields.

It happens because ASP.NET MVC use DefaultModelBinder by default which deals with properties but not with fields when map posted form values.

Of course you can use properties instead of fields wherever you need model bindings. But it is an annoying limitation.

ASP.NET MVC allows us to override both the default model binder, as well as add custom model binders, through the ModelBinders static class:

ModelBinders.Binders.DefaultBinder = new SomeCustomDefaultBinder();
ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());

There are more blog entries about ASP.NET MVC Model Binding
6 Tips for ASP.NET MVC Model Binding
A better Model Binder