C# 如何防止在模型中的某些属性上使用自定义模型绑定器。ASP.NETMVC
我已经创建了一个自定义模型活页夹,并在Global.asax中注册了decimal和decimal?类型。我需要防止某些属性绑定值。我怎么做? 请看下面的代码: 全球卫星C# 如何防止在模型中的某些属性上使用自定义模型绑定器。ASP.NETMVC,c#,asp.net,asp.net-mvc,asp.net-mvc-5,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 5,我已经创建了一个自定义模型活页夹,并在Global.asax中注册了decimal和decimal?类型。我需要防止某些属性绑定值。我怎么做? 请看下面的代码: 全球卫星 ModelBinders.Binders[typeof(decimal)] = new DecimalModelBinder(); ModelBinders.Binders[typeof(decimal?)] = new DecimalModelBinder(); DecimalModelBinder.CS publ
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只适用于一个属性,但我已在全球注册了它。请提出建议。我认为您应该能够将其绑定到特定型号,而不是所有型号。检查这个-我认为这应该对你有所帮助,尽管我怀疑它是否只适用于某个特定的领域。这个解释只是关于整个模型。我的模型中有一个很长的属性列表,因此我无法为它编写另一个模型绑定器。我只需要防止DecimalModelBinder用于decimal类型的一些属性。我认为您应该能够将它绑定到一个特定的模型,而不是所有的模型。检查这个-我认为这应该对你有所帮助,尽管我怀疑它是否只适用于某个特定的领域。这个解释只是关于整个模型。我的模型中有一个很长的属性列表,因此我无法为它编写另一个模型绑定器。我只需要防止DecimalModelBinder对decimal类型的几个属性执行操作。