gpt4 book ai didi

c# - 如何仅使用 InvariantCulture 渲染某些特定模型字段,而其余部分继续使用用户区域性?

转载 作者:太空狗 更新时间:2023-10-29 21:47:10 24 4
gpt4 key购买 nike

我在 asp.net mvc View 上有几个隐藏的输入。它们的值包含 double 类型的对象。我希望它们使用 InvariantCulture 呈现,因为它们用于在客户端上提供给 api(谷歌地图)。就像现在一样,它们使用逗号 (,) 作为小数点分隔符呈现,而 API 需要点 (.) 作为小数点分隔符。

最好的解决方案是,如果我可以在模型属性的 DisplayFormat 数据注释属性中指定文化,但我认为这是不可能的:

public class Position
{
[DisplayFormat(DataFormatString="{0:G}, CultureInfo.InvariantCulture")]
public double Latitude;
...
}

我也不能在我的 Application_Start 方法中将 CurrentCulture 设置为 InvariantCulture,因为屏幕上还有其他值处于适当的用户文化中。

那么,有没有一种方法可以暂时改变当前文化,就在我为那个特定属性执行 Html.HiddenFor(Model => Model.Latitude) 之前,然后再重置它?

或者还有其他更好的方法吗?与此相关的最佳做法是什么?

最佳答案

实现此目的的一种方法是编写自定义编辑器模板 ~/Views/Shared/EditorTemplates/InvariantDouble.cshtml:

@{
object modelValue = string.Format(
System.Globalization.CultureInfo.InvariantCulture,
ViewData.ModelMetadata.DisplayFormatString,
ViewData.ModelMetadata.Model
);
}
@Html.TextBox("", modelValue, new { @class = "text-box single-line" })

然后在你的模型上:

[DisplayFormat(DataFormatString="{0:G}")]
[UIHint("InvariantDouble")]
public double Latitude;

最后是您的观点:

@Html.EditorFor(x => x.Latitude)

或者如果您希望应用程序中的所有替身都像这样使用 ~/Views/Shared/EditorTemplates/Double.cshtml 而不使用任何 UIHint

关于c# - 如何仅使用 InvariantCulture 渲染某些特定模型字段,而其余部分继续使用用户区域性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5300525/

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