Created
April 5, 2019 11:37
-
-
Save mustafadagdelen/d864b935e19510a9c3e40c1f30c2ca83 to your computer and use it in GitHub Desktop.
Dotnet core decimal model binder problem fix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Globalization; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Mvc.ModelBinding; | |
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; | |
namespace BA.ECommerce.Client.Utility | |
{ | |
public class InvariantDecimalModelBinderProvider : IModelBinderProvider | |
{ | |
public IModelBinder GetBinder(ModelBinderProviderContext context) | |
{ | |
if (context == null) throw new ArgumentNullException(nameof(context)); | |
if (!context.Metadata.IsComplexType && (context.Metadata.ModelType == typeof(decimal) || context.Metadata.ModelType == typeof(decimal?))) | |
{ | |
return new InvariantDecimalModelBinder(context.Metadata.ModelType); | |
} | |
return null; | |
} | |
} | |
public class InvariantDecimalModelBinder : IModelBinder | |
{ | |
private readonly SimpleTypeModelBinder _baseBinder; | |
public InvariantDecimalModelBinder(Type modelType) | |
{ | |
_baseBinder = new SimpleTypeModelBinder(modelType); | |
} | |
public Task BindModelAsync(ModelBindingContext bindingContext) | |
{ | |
if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); | |
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); | |
if (valueProviderResult != ValueProviderResult.None) | |
{ | |
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); | |
var valueAsString = valueProviderResult.FirstValue; | |
decimal result; | |
// Use invariant culture | |
if (decimal.TryParse(valueAsString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out result)) | |
{ | |
bindingContext.Result = ModelBindingResult.Success(result); | |
return Task.CompletedTask; | |
} | |
} | |
// If we haven't handled it, then we'll let the base SimpleTypeModelBinder handle it | |
return _baseBinder.BindModelAsync(bindingContext); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services.AddMvc(options => | |
{ | |
options.ModelBinderProviders.Insert(0, new InvariantDecimalModelBinderProvider()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment