我有十进制数问题.
如果我在文本框中使用.(点)而不是(逗号),它在控制器中为空.
我知道它是一个语言问题,因为在西班牙语中我们使用逗号而不是小数点,但我需要使用点.
有可能改变这个吗?
这很奇怪,因为在控制器中我必须使用.(点)表示小数,即:
我能做float x = 3.14但我不能这样float x = 3,14做我不明白这个...在某些情况下我必须使用点...在其他情况下我必须使用逗号...
这是我的代码:
在模型中:
[Display(Name = "Total")]
public double Total { get; set; }
Run Code Online (Sandbox Code Playgroud)
在视图中:
@Html.EditorFor(model => model.Total, new { id = "Total", htmlAttributes = new {@class = "form-control" } })
Run Code Online (Sandbox Code Playgroud)
在控制器中:
public ActionResult Create([Bind(Include = "ID,Codigo,Fecha,Trabajo,Notas,BaseImponible,Iva,Total,Verificado,FormaDePagoID,ClienteID")] Presupuesto presupuesto)
{
Run Code Online (Sandbox Code Playgroud)
谢谢大家.我发现这个来自Phil Haack的代码效果非常好.
在项目的任何文件夹中创建一个类
public class ModelBinder
{
public class DecimalModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
object result = null;
// Don't do this here!
// It might do bindingContext.ModelState.AddModelError
// and there is no RemoveModelError!
//
// result = base.BindModel(controllerContext, bindingContext);
string modelName = bindingContext.ModelName;
string attemptedValue =
bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;
// Depending on CultureInfo, the NumberDecimalSeparator can be "," or "."
// Both "." and "," should be accepted, but aren't.
string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
string alternateSeperator = (wantedSeperator == "," ? "." : ",");
if (attemptedValue.IndexOf(wantedSeperator) == -1
&& attemptedValue.IndexOf(alternateSeperator) != -1)
{
attemptedValue =
attemptedValue.Replace(alternateSeperator, wantedSeperator);
}
try
{
if (bindingContext.ModelMetadata.IsNullableValueType
&& string.IsNullOrWhiteSpace(attemptedValue))
{
return null;
}
result = decimal.Parse(attemptedValue, NumberStyles.Any);
}
catch (FormatException e)
{
bindingContext.ModelState.AddModelError(modelName, e);
}
return result;
}
}
}
Run Code Online (Sandbox Code Playgroud)
将其添加到Global.asax中的Application_Start()方法
ModelBinders.Binders.Add(typeof(decimal), new ModelBinder.DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new ModelBinder.DecimalModelBinder());
Run Code Online (Sandbox Code Playgroud)
现在使用十进制类型而不是浮点数或双倍,一切都会好起来!! 谢谢伙伴见到你!
您的控制器使用 C#。语言特定声明它.是小数分隔符。时期。这不是特定于语言的,仅此而已。
您的数据库或 UI(使用服务器的语言设置)可能会使用与 C# 使用的默认(美国)语言设置不同的其他小数分隔符。这就是为什么你必须,在那里使用分隔符。
| 归档时间: |
|
| 查看次数: |
8186 次 |
| 最近记录: |