简体   繁体   中英

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

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

Everything works fine if I dont use a comma. ie

50.00 gets saved and displayed as 50 500000 gets saved and displayed as 500,000

however, if I try to enter 500,000 ie with a comma then I get the following error:

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

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

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

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

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

You must change

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

to

 [DataType(DataType.Currency)]

The problem is solved!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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