如何在模型中的某些属性上防止自定义模型绑定器。 ASP.NET MVC

时间:2016-11-29 11:54:20

标签: c# asp.net asp.net-mvc asp.net-mvc-5

我创建了一个自定义模型绑定器并在Global.asax中注册了十进制和十进制?类型。我需要阻止某些属性绑定值。我该怎么做? 请看下面的代码:

Globasl.asax

ModelBinders.Binders[typeof(decimal)] = new DecimalModelBinder();
ModelBinders.Binders[typeof(decimal?)] = new DecimalModelBinder();

DecimalModelBinder.CS

    public class DecimalModelBinder : IModelBinder
{
    // adapted from: http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }

        if (bindingContext == null)
        {
            throw new ArgumentNullException("bindingContext");
        }

        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var modelState = new ModelState { Value = valueProviderResult };

        object actualValue = null;
        try
        {
            var attemptedValue = (valueProviderResult.AttemptedValue ?? string.Empty)
                .Replace(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator, string.Empty)
                .Replace(Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol, string.Empty);

            actualValue = Convert.ToDecimal(attemptedValue, CultureInfo.InvariantCulture);
        }
        catch (Exception exception)
        {
            modelState.Errors.Add(exception);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}

TestViewModel.CS

    public class TestViewModel 
{


    [DisplayName("Percentage")]
    public decimal? Percent { get; set; }

    [FixedFeeRequired]
    [DisplayName("Fixed Fee")]
    public decimal? FixedValue { get; set; }
}

我希望DecimalModelBinder仅应用于一个属性,但我已在全局注册它。请建议。

0 个答案:

没有答案