出于某种原因,当我将此JSON发送到某个操作时:
{"BaseLoanAmount": 5000}
Run Code Online (Sandbox Code Playgroud)
应该绑定到具有名为"BaseLoanAmount"的十进制属性的模型,它不绑定,它只保持0.但是如果我发送:
{"BaseLoanAmount": 5000.00}
Run Code Online (Sandbox Code Playgroud)
它确实绑定了属性,但为什么呢?如果没有十进制数,不能将5000转换为十进制事件吗?
ryu*_*ice 73
在进入asp.net mvc的源代码之后,似乎问题是对于转换asp.net mvc使用框架的类型转换器,由于某种原因返回false进行int到十进制转换,我最终使用了自定义模型绑定器小数的提供者和模型绑定器,你可以在这里看到它:
public class DecimalModelBinder : DefaultModelBinder
{
#region Implementation of IModelBinder
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult.AttemptedValue.Equals("N.aN") ||
valueProviderResult.AttemptedValue.Equals("NaN") ||
valueProviderResult.AttemptedValue.Equals("Infini.ty") ||
valueProviderResult.AttemptedValue.Equals("Infinity") ||
string.IsNullOrEmpty(valueProviderResult.AttemptedValue))
return 0m;
return Convert.ToDecimal(valueProviderResult.AttemptedValue);
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
要注册此ModelBinder,只需将以下行放入Application_Start():
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 12
尝试像这样发送:
{ "BaseLoanAmount": "5000" }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17072 次 |
| 最近记录: |