.NET MVC 3自定义小数?模型绑定 [英] .NET MVC 3 Custom Decimal? Model Binder
问题描述
在我的模型中,我有以下小数?属性:
In my model, I have the following decimal? property:
public decimal? Budget { get; set; }
我意识到我需要小数其中哈克在以下链接提供的自定义模型绑定:<一href=\"http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx\">http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx.
我修改了code,这样,如果在传递的价值确实包含货币符号和/或逗号,然后我脱光,然后尝试将其转换为十进制。这工作,但被我的属性是可空小数类型,我也希望它什么都不接受,并沿其快乐的方式插入一个空到我的数据库列移动。现在它插入一个0.00元。我知道我错过了我的code的东西,但我有一个脑冻。
I have modified his code so that if the value being passed in does contain a currency symbol and/or comma then I strip it and then try to convert it to a decimal. This works but being that my property is a nullable decimal type, I also want it to accept nothing and move along its merry way inserting a null into that column in my database. Right now it inserts a 0.00. I know I'm missing something in my code but am having a brain freeze.
下面是粘合剂code:
Here's the binder code:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
object newValue = null;
try
{
if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
{
newValue = valueResult.AttemptedValue.Replace("$", "").Replace(",", "");
}
actualValue = Convert.ToDecimal(newValue, CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
再次目标是有小数?行为与平常不同,但如果有其中包含一个货币符号和/或逗号一个值,它可以被转换为十进制然后返回
Again, the goal is to have decimal? act like it usually does but if there is a value which contains a currency symbol and/or comma and it can be converted to a decimal then to return that.
感谢
推荐答案
在try块,我认为你需要像
In the try block, I think you need something like
string valToCheck = valueResult.AttemptedValue;
if(valToCheck == string.Empty)
{
actualValue = null;
}
else
{
actualValue = Convert.ToDecimal(valToCheck.Replace("$", string.Empty), CultureInfo.InvariantCulture);
}
在您的code,你总是设置actualValue到ToDecimal()的结果。
In your code, you are always setting actualValue to the result of ToDecimal().
这篇关于.NET MVC 3自定义小数?模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!