简体   繁体   English

Html.EditorFor 用于带逗号的十进制字段

[英]Html.EditorFor for a decimal field with commas

Hi I have a decimal field defined for price as follows:嗨,我为价格定义了一个小数字段,如下所示:

[Required(ErrorMessage = "Asking Price/Rent is required.")]
[Display(Name = "Asking Price/Rent*")]
[DisplayFormat(DataFormatString = "{0:N0}", ApplyFormatInEditMode = true)]
public decimal Price {get; set;}

I have an editor field for this in my view as follows:在我看来,我有一个编辑器字段,如下所示:

<div class="editor-label">
    @Html.LabelFor(model => model.Property.Price)
    @Html.EditorFor(model => model.Property.Price)
</div>

I have the following globalisation culture set in web.config我在 web.config 中设置了以下全球化文化

<globalization uiCulture="en-GB" culture="en-GB" />

Everything works fine if I dont use a comma.如果我不使用逗号,一切正常。 ie IE

50.00 gets saved and displayed as 50 500000 gets saved and displayed as 500,000 50.00 被保存并显示为 50 500000 被保存并显示为 500,000

however, if I try to enter 500,000 ie with a comma then I get the following error:但是,如果我尝试输入 500,000 即用逗号输入,则会出现以下错误:

The value '500,000' is not valid for Asking Price/Rent*.

I want the editor field to be able to take commas as I would expect most users to use comma while putting in Price in the form.我希望编辑器字段能够使用逗号,因为我希望大多数用户在表单中输入价格时使用逗号。

How do I allow use of comma while entering numbers?如何在输入数字时允许使用逗号?

I have a solution that might work with your case first we are going to use some javascript to help us in that我有一个可能适用于您的情况的解决方案,首先我们将使用一些 javascript 来帮助我们

leave textbox as you implemented above and add label beside it blank label保留上面实现的文本框并在其旁边添加标签空白标签

with javascript we parse the number entered in textbox and convert it to the new format with comma as you want it to display使用 javascript,我们解析在文本框中输入的数字,并将其转换为您希望显示的逗号新格式

with this way you gain the full feature of adding data annotation validation and show the number formatted to users as well通过这种方式,您可以获得添加数据注释验证的全部功能,并向用户显示格式化的数字

the following links my help you as well in this以下链接我也可以帮助您

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx

http://yuilibrary.com/yui/docs/datatype/#formattingnumbers http://yuilibrary.com/yui/docs/datatype/#formattingnumbers

You must change你必须改变

[DisplayFormat(DataFormatString = "{0:N0}", ApplyFormatInEditMode = true)]

to

 [DataType(DataType.Currency)]

The problem is solved!问题已经解决了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM