【问题标题】:ASP.NET MVC C# DisplayFormat IssueASP.NET MVC C# DisplayFormat 问题
【发布时间】:2017-01-31 05:18:29
【问题描述】:

我直接进入正题。

我正在尝试将 Monthly Income 显示为只有 2 位小数。

我尝试过使用DisplayFormat,但是当我将它添加到文本框时它不起作用。

型号

public class AgentModel
{

    [Display(Name = "Monthly Income")]
    [DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
    public decimal MonthlyIncome { get; set; }
}

查看

//this input display the two decimal
@Html.EditorFor(m => m.MonthlyIncome, new { htmlAttributes = new { @class = "form-control" } })

//this one display 5 decimal
@Html.TextBoxFor(m => m.MonthlyIncome, new { @class = "form-control"})

我很困惑这两个输入之间有什么区别。 我正在使用DataFormat,因为我希望将格式集中在我的模型上。并且不要使用此代码@string.Format("{0:N2}",decimal.Round(agent.MonthlyIncome, 2, MidpointRounding.AwayFromZero)) 来限制小数位。因为如果我这样做的话,我会在我所有的观点中这样做。

我也试过只输出monthly income的值

<td>@agent.MonthlyIncome</td>

这仍然返回 5 位小数。

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    要使用TextBoxFor() 显示格式化值,请使用this overload

    @Html.TextBoxFor(m => m.MonthlyIncome, "{0:0.00}", new { @class = "form-control"})
    

    第二个参数是格式字符串。请注意,DisplayFormatAttribute 仅在使用 EditorFor()DisplayFor() 时才会受到尊重

    另请注意,&lt;td&gt;@Html.DisplayFor(m =&gt; m.MonthlyIncome)&lt;/td&gt; 将以正确的格式呈现值。

    【讨论】:

    • 我明白了...,所以我需要在我拥有的每个视图上添加格式参数?好像我使用 EditorFor 它会自动在我的模型上添加数据注释..
    • 如果你想使用TextBoxFor(),那么可以。但是您是否有理由不想使用 EditorFor() - 您问题中的 2 个实现将生成相同的 html。
    • 嗨,steph..我将使用EditorFor,因为它在编辑文本框的格式时很有效....但是,我怎样才能显示@的格式987654331@ 如果我尝试将其添加到我的表格中,就像&lt;td&gt;@agent.MonthlyIncome&lt;/td&gt; 因为它仍然会显示 5 个小数位,这与使用EditorFor 时不同,它会将其转换为文本框并转换显示?
    • 看我回答的最后一段
    • 当我循环数据时怎么样......我得到了一堆monthlyIncome
    【解决方案2】:

    DisplayFormat 仅适用于 EditorFor/DisplayFor。看看this fiddle for mvc。

    型号

    使用系统; 使用 System.ComponentModel.DataAnnotations;

    namespace HelloWorldMvcApp
    {
        public class SampleViewModel
        {
            [Required]
            [MinLength(10)]
            [MaxLength(100)]
            [Display(Name = "Ask Magic 8 Ball any question:")]
            public string Question { get; set; }
    
            [DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
            public decimal MonthlyIncome { get; set; }
    
            //See here for list of answers
            public string Answer { get; set; }
        }
    }
    

    控制器

    using System;
    using System.Web.Mvc;
    using System.Collections.Generic;
    
    namespace HelloWorldMvcApp
    {
        public class HomeController : Controller
        {
            [HttpGet]
            public ActionResult Index()
            {
                var s = new SampleViewModel();
                s.MonthlyIncome = 1000;
                return View(s);
            }
    
    
            [HttpPost]
            public JsonResult GetAnswer(string question)
            {               
                int index = _rnd.Next(_db.Count);
                var answer = _db[index];
                return Json(answer);
            }
    
            private static Random _rnd = new Random();
    
            private static List<string> _db = new List<string> { "Yes", "No", "Definitely, yes", "I don't know", "Looks like, yes"} ;
        }
    }
    

    查看

    @model HelloWorldMvcApp.SampleViewModel
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    <!-- template from http://getbootstrap.com/getting-started -->
    
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>Bootstrap 101 Template</title>
    
            <!-- CSS Includes -->
            <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    
            <style type="text/css">
    
                .field-validation-error {
                    color: #ff0000;
                }
    
            </style>
        </head>
    
        <body>
            <div class="container">
                <div class="col-md-6 col-md-offset-3">
                    <h1>Hello Stranger</h1>
    
                    @using (Html.BeginForm())
                    {
                        <div class="form-group">
                            @Html.LabelFor(m => m.Question)
                            @Html.TextBoxFor(model => model.Question, new {@class="form-control"}) 
                            @Html.ValidationMessageFor(model => model.Question)
                        </div>
                        @Html.DisplayFor(m => m.MonthlyIncome)
    
                        <button type="button" class="btn btn-success submit">Ask</button>
                    }
    
                    <br/><br/>
                    <div class="alert alert-warning fade">
                        <img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
                        <strong><span class="alert-content"></span></strong>
                    </div>
                </div>
            </div>
    
            <!-- JS includes -->
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
            <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    
            <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
            <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
    
            <script type="text/javascript">
    
                function openAlert(txt) {
                    $('.alert-content').text(txt);
                    $('.alert').addClass('in');
                }
    
                function closeAlert() {
                    $('.alert').removeClass('in');
                }
    
                $(function(){
                    var answer = '@Model.Answer';
    
                    if(answer && answer != '') 
                        openAlert(answer);
    
                    $('#Question').change(closeAlert);
                    $('#Question').keyup(closeAlert);
    
                    $('.submit').click(function(){
                        if($('form').valid()) {
    
                            $.ajax({
                                url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
                                data: {Answer: '', Question: $('#Question').val()},
                                    type: 'POST',
                                    dataType: 'json',
                                    contentType: "application/json; charset=utf-8",
                                    success: function(resp) {
                                    openAlert(resp);
                            }});
                        }
                        else {
                            closeAlert();
                        }
                    });
    
                });
    
            </script>
        </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2016-08-06
      相关资源
      最近更新 更多