Monday, December 14, 2009

ASP.NET MVC XML Model Binder

Update 12/14/2011
This is one of my most highly viewed posts. Unfortunately, this post applies to version 1 of ASP.NET MVC (it might also work with version 2 with some small modifications). If that is what you are looking for, then please read on! Otherwise, for more relevant coverage of this topic I recommend Jimmy Bogard's post

I needed a way to receive raw XML in my action methods, rather than form-encoded values. Model binding makes it a piece of cake:



In my action method all I have to do is apply the model binder attribute:



Now the edit action receives an XML string. Even better, I can get a strongly typed object if it is serializable:



Now my action method looks like this:



The model binder attribute is a little too verbose for my taste, so I wrote a custom model binder attribute:



Finally my action method is nice and readable:


No comments:

Post a Comment