gpt4 book ai didi

c# - 更改整数的默认 NumberStyles?

转载 作者:太空狗 更新时间:2023-10-29 22:01:02 25 4
gpt4 key购买 nike

我有一个具有整数属性的模型。当使用 23443 提交模型时,模型绑定(bind)器运行良好并且该值在操作中可用。但是,如果提交的模型带有千位分隔符,如 23,443,则不会解析该值且该属性为零。但我发现小数类型的属性可以有千位分隔符,它会正确解析和填充。

我发现 by default Int32.Parse() doesn't parse thousands separator但是 Decimal.Parse() 确实允许使用千位分隔符。我不想写这样的支票:

public ActionResult Save(Car model, FormCollection form) {
Int32 milage;
if(model.MyProperty == 0 && Int32.TryParse(form["MyProperty"], NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out milage) {
model.MyProperty = milage;
} else
ModelState.AddModelError("Invalid", "Property looks invalid");

[...]
}

每次我处理这些字段。它看起来很难看,并且将所有验证都移出了模型属性。将属性的类型更改为 decimal 只是为了使模型绑定(bind)工作似乎不是一个聪明的主意。当我查看模型联编程序时,它看起来像是在使用 TypeConverter 来完成从字符串到类型的转换。还有它looks like Int32Converter uses Int32.Parse() with NumberStyles.Integer .

有没有办法改变 Int32Converter 的行为,以允许默认解析千位分隔符?也许在整个应用程序中覆盖 Int32.Parse() 上的默认 NumberStyles?还是添加我自己的模型联编程序以使用 NumberStyles.AllowThousands 解析整数是唯一/正确的操作过程?

最佳答案

我认为,您可以为 int 类型添加自定义 Binder 。

演示:http://dotnetfiddle.net/VSMQzw

有用的链接:

已更新

基于被黑客攻击的文章:

using System;
using System.Globalization;
using System.Web.Mvc;

public class IntModelBinder : IModelBinder
{
#region Implementation of IModelBinder

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
bindingContext.ModelState[bindingContext.ModelName] = modelState;

object actualValue = null;
try
{
actualValue = Int32.Parse(valueResult.AttemptedValue, NumberStyles.Number, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}

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

#endregion
}

然后在 Application_Start 事件中(可能在 Global.asax 中),添加:

ModelBinders.Binders.Add(typeof(int), new IntModelBinder());

关于c# - 更改整数的默认 NumberStyles?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21189158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com