简体   繁体   中英

How do I properly post a decimal value in a Razor View?

I have a POCO model as follows:

public class Tool
{
    [Key]
    public int ID { get; set; }

    public int QtyOnHand { get; set; }


    [DisplayFormat(DataFormatString = "{0:#.####}")]
    public decimal SizeUS { get; set; }
    public string Location { get; set; }
    public int OriginalID { get; set; }


    [NotMapped]
    public bool Selected { get; set; }

    [NotMapped]
    public bool Selectable { get; set; }

}

In my Razor View I have:

@Html.EditorFor(model => model.SizeUS)                    
@Html.ValidationMessageFor(model => model.SizeUS)

The problem that I have is the SizeUS value gets rounded to the 1/100th when posted to the controller. I want to be able to post a value of up to 1/1000th or maybe 1/10000th. How would I do so ?

It's how the decimal editor is defined for currency reasons:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<script runat="server">
    private object FormattedValue {
        get {
            if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model) {
                return String.Format(System.Globalization.CultureInfo.CurrentCulture,
                                     "{0:0.00}",
                                     ViewData.ModelMetadata.Model);
            }
            return ViewData.TemplateInfo.FormattedModelValue;
        }
    }
</script>

This template displays decimal values with 2 digits of precision by default, since most users will use decimal values to represent currency. Note that it only does this if you haven't applied a format string (which is the purpose of the check in the if statement). <%= Html.Encode(FormattedValue) %>

ref: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html

You can either use double instead, create your own editor template, or simply write out a HTML input control.

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