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:

1 comment:

  1. Wow. Awesome article. Please do more articles like this in the future. Very informational and knowledgeable. I will expect more from you in the future. For now i will just bookmark your page and surely I'm gonna come back later to read more. Thank you to the writer!