http://stackoverflow.com/questions/24439997/nancy-decimal-property-binding-not-working
Oh noes! ---> Nancy.ModelBinding.ModelBindingException: Unable to bind to type: Nancy.Models.SomeModel
at Nancy.ModelBinding.DefaultBinder.Bind(NancyContext context, Type modelType, Object instance, BindingConfig configuration, String[] blackList)
at Nancy.ModelBinding.DynamicModelBinderAdapter.TryConvert(ConvertBinder binder, Object& result)
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at Nancy.ModelBinding.ModuleExtensions.Bind[TModel](INancyModule module)
at KBZServisNancy.Modules.SomeModule.<.ctor>b__2(Object x) in d:\Nancy\Modules\SomeDecimalModule.cs:line 38
at CallSite.Target(Closure , CallSite , Func`2 , Object )
at Nancy.Routing.Route.<>c__DisplayClass4.b__3(Object parameters, CancellationToken context)
--- End of inner exception stack trace ---
at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)
at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)
์ด๊ฒ์ด ๋ฒ๊ทธ ์ธ ๊ฒ ๊ฐ์ต๋๋ค. ๊ฒฝ๋ก์ ์ญ์ง์๋ก ์ง์ ์๋ํ์ง๋ง ๋์ผํ ์์ธ๊ฐ ๋ฐ์ํ์ต๋๋ค.
DecimalConverter.ConvertFrom์ ํ์ฌ ๋ฌธํ์ ์ปจํ ์คํธ์์ ์ฌ์ฉ๋๋ฉฐ ํฐํค ๋ฌธํ์์๋ "1.1" ๋์ "1,1"์ ๊ธฐ๋ํฉ๋๋ค. InvariantCulture์ ํจ๊ป ConvertFrom์ ์ฌ์ฉํ์ฌ ๋์ฒด ์ ๋ต์ ๊ตฌํํ ์ ์์ต๋๋ค. ๋์ด์ค๊ธฐ ์์ฒญ์ ์๋ฝํฉ๋๊น?
๊ทธ๋ฅ ITypeConverter
``` C#
///
/// InvariantCulture๋ฅผ ์ฌ์ฉํ์ฌ ์ซ์ ์ ํ์ ๋ณํํ๋ Nancy ๋ณํ๊ธฐ.
///
๊ณต๊ฐ ํด๋์ค NancyNumericConverter : ITypeConverter
{
public bool CanConvertTo(์ ํ ๋์ ์ ํ, BindingContext ์ปจํ
์คํธ)
{
return destinationType.IsNumeric();
}
public object Convert(string input, Type destinationType, BindingContext context)
{
if (string.IsNullOrEmpty(input))
{
return null;
}
return System.Convert.ChangeType(input, destinationType, CultureInfo.InvariantCulture);
}
}
```
๊ทธ๋ฅ
ITypeConverter
์ ์์ ๊ฐ์ฌ๋๋ฆฝ๋๋ค. ์ ์๋ํฉ๋๋ค!
ํ์ง๋ง System.Convert.ChangeType
๋ nullable ํ์์ ์ง์ํ์ง ์๋ ๊ฒ ๊ฐ์ต๋๋ค.
๋ค์๊ณผ ๊ฐ์ด Nullable.GetUnderlyingType
์ฌ์ฉํ์ฌ ์์ ํ ์ ์์ต๋๋ค.
/// <summary>
/// Nancy converter to convert numeric types with InvariantCulture.
/// </summary>
public class InvariantCultureNumericConverter : ITypeConverter
{
public bool CanConvertTo(Type destinationType, BindingContext context)
{
return destinationType.IsNumeric();
}
public object Convert(string input, Type destinationType, BindingContext context)
{
if (string.IsNullOrEmpty(input))
{
return null;
}
destinationType = Nullable.GetUnderlyingType(destinationType) ?? destinationType;
return System.Convert.ChangeType(input, destinationType, CultureInfo.InvariantCulture);
}
}
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
๊ทธ๋ฅ
ITypeConverter
``` C#
///
/// InvariantCulture๋ฅผ ์ฌ์ฉํ์ฌ ์ซ์ ์ ํ์ ๋ณํํ๋ Nancy ๋ณํ๊ธฐ.
///
๊ณต๊ฐ ํด๋์ค NancyNumericConverter : ITypeConverter
{
public bool CanConvertTo(์ ํ ๋์ ์ ํ, BindingContext ์ปจํ ์คํธ)
{
return destinationType.IsNumeric();
}
```