Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

InvariantNumberModelBinderProvider.cs

using System.Globalization;
using System.Numerics;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace Nop.Web.Framework.Mvc.ModelBinding.Binders;

/// 
/// Represents a model binder provider for binding numeric types
/// 
public partial class InvariantNumberModelBinderProvider : IModelBinderProvider
{
    #region Fields

    protected static readonly HashSet _integerTypes =
    [
        typeof(int), typeof(long), typeof(short), typeof(sbyte),
    typeof(byte), typeof(ulong), typeof(ushort), typeof(uint), typeof(BigInteger)
    ];

    protected static readonly HashSet _floatingPointTypes =
    [
        typeof(double), typeof(decimal), typeof(float)
    ];

    #endregion

    /// 
    /// Creates a model binder
    /// 
    /// Context object
    /// Instance of model binder for floating-point types
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        var modelType = context.Metadata.UnderlyingOrModelType;

        if (modelType is null)
            return null;

        if (_floatingPointTypes.Contains(modelType))
            return new InvariantNumberModelBinder(NumberStyles.Float, new FloatingPointTypeModelBinderProvider().GetBinder(context));

        if (_integerTypes.Contains(modelType))
            return new InvariantNumberModelBinder(NumberStyles.Integer, new SimpleTypeModelBinderProvider().GetBinder(context));

        return null;
    }
}