Tuesday, August 27, 2013

Binding enum arrays with MVC models

The simplicity of model binding in the MVC framework makes it a powerful and pleasant framework to send models up and down to views. But a little short coming prevents the usage of enum arrays and raising maintainability in my opinion. MVC 4 cannot convert / materialize enum values to an array when used in a model. To put it correctly, there is no standard type converter for the job.

This issue manifested when I was working on a checkbox list of statuses that could be selected as a filter. This would then be posted as a comma separated parameter value to be set on the model object. Which is finally used in a LINQ query.

Monday, August 26, 2013

Convert all the (C#) types!

Well, almost all. So here is an incredible handy conversion class that I always carry around in all my projects. It has never failed me, never let me down... you get the idea. Although I cannot take full credit for it, thank Steven for the initial setup, I have done some minor tweaks in the past.

Usage is pretty straight forward. Call the (generic) method, put in a string in the correct format, converted and casted type comes out.

var value = Conversion.AsValue<int>("123"); 
//// Returns 123 as int

var value = Conversion.AsValue<int?>("123"); 
//// Returns 123 as nullable int

var value = Conversion.AsValue<int?>(""); 
//// Returns null (handy for webrequest parameters)