asp.net-mvc – 如何在ASP.NET MVC控制器中设置十进制分隔符?
发布时间:2020-05-23 18:52:00 所属栏目:asp.Net 来源:互联网
导读:我正在与 NerdDinner应用程序试图教自己ASP.NET MVC。然而,我偶然发现了全球化的问题,其中我的服务器以逗号作为小数分隔符来呈现浮点数,但虚拟地球地图需要它们带有点,这会导致一些问题。 我已经解决了the issue with the mapping JavaScript in my views
|
我正在与 NerdDinner应用程序试图教自己ASP.NET MVC。然而,我偶然发现了全球化的问题,其中我的服务器以逗号作为小数分隔符来呈现浮点数,但虚拟地球地图需要它们带有点,这会导致一些问题。 我已经解决了the issue with the mapping JavaScript in my views,但如果我现在尝试发布一个编辑的晚餐条目与点作为十进制分隔符控制器失败(抛出InvalidOperationException)更新模型(在UpdateModel()metod)。我觉得我必须在控制器的某个地方设置正确的文化,我在OnActionExecuting()中尝试过,但是没有帮助。 解决方法我刚刚在一个真正的项目中重新审视了这个问题,最终找到了一个可行的解决方案。正确的解决方案是使用十进制类型的自定义模型绑定(如果使用十进制,则为十进制):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;
}
}
然后在Application.Start()中的Global.asax.cs中: ModelBinders.Binders.Add(typeof(decimal),new DecimalModelBinder()); ModelBinders.Binders.Add(typeof(decimal?),new DecimalModelBinder()); 请注意,代码不是我的,我实际上是在Kristof Neirynck的博客here中找到的。我刚刚编辑了几行,并添加了特定数据类型的binder,而不是替换默认的绑定。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Asp.Net Cache缓存使用代码
- asp.net-mvc – SignalR和MVC包
- ASP.NET Web应用程序 – WebResource.axd和ScriptResource.
- 在asp.net-mvc中,在不影响其他用户的情况下执行昂贵操作的正
- asp.net – 您在实施/使用WebDAV方面有哪些经验?
- asp.net-web-api – Web API 2 OWIN承载令牌认证 – Access
- 使用带数组的ASP.NET中继器?
- 认证 – asp.net mvc 3:Page.User.IsInRole(“xy”)返回nu
- 如何在ASP.Net MVC中实现ReverseAJAX(Comet)
- asp.net – 在2K3构建服务器上的单元测试中不允许使用’应用
推荐文章
站长推荐
- asp.net-mvc – ASP.NET MVC 5自定义错误页面
- asp.net – Intranet / Internet的Windows身份验
- C# 中的委托和事件 [转载]
- ASP.NET Webforms验证框架的建议
- asp.net-mvc – ASP.net MVC DropDownList预选项
- 如何检测ASP.NET应用程序中的SqlServer连接泄漏?
- asp.net-mvc – FormsAuthentication.SetAuthCoo
- 如何在ASP.NET中设置TextBox中的对齐中心?
- asp.net – Thread.CurrentPrincipal在使用WebGe
- 为什么NuPack生成的NinjectMVC3.cs无法编译? (或
热点阅读
