Daniel Hoelbling-Inzko talks about programming
While reading through ScottGu’s announcement of the ASP.NET MVC 2 Preview 1 I noticed this rather interesting little feature that’s in there:
MonoRail is much smarter about action methods than MVC so there are already things going on with default values through routing etc. But this particular thing wasn’t in the framework until now. So I took Ken Egozi’s sample about using IParameterBinder to implement the DefaultValueAttribute in MonoRail.
The result in syntax is identical to ASP.NET MVC 2 P1 and it was very easy to do:
public void Browse([DefaultValue("beer")] string category, [DefaultValue(1)] int page) { }
How is this done? Well, I suggest you read Ken Egozi’s post since he does a much better job at explaining that thing. Anyway, here is the code to make that happen:
using System; using System.Reflection; using Castle.MonoRail.Framework;[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class DefaultValueAttribute : Attribute, IParameterBinder { private readonly object value; public DefaultValueAttribute(object value) { this.value = value; }
public int CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo) { var token = context.Request[parameterInfo.Name]; if (CanConvert(parameterInfo.ParameterType, token)) return 10; return 0; } private static bool CanConvert(Type targetType, string token) { if (token == null) return false;
try { Convert.ChangeType(token, targetType); return true; } catch (FormatException) { return false; } }
public object Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo) { string token = context.Request[parameterInfo.Name]; Type type = parameterInfo.ParameterType; if (CanConvert(type, token)) return Convert.ChangeType(token, type); return value; } }