ASP.NET MVC C#DisplayFormat问题

时间:2017-01-31 05:18:30

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

我直截了当地说到这一点。

我试图显示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位小数。

2 个答案:

答案 0 :(得分:6)

要使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div> <h2>Div containing UL</h2> <ul> <li data-src="http://bhuck.com/svg/layers.svg" style="list-style-image: url(http://bhuck.com/svg/layers.svg)">List with</li> <li data-src="http://bhuck.com/svg/server.svg" style="list-style-image: url(http://bhuck.com/svg/server.svg)">style images</li> <li data-src="http://bhuck.com/svg/share.svg" style="list-style-image: url(http://bhuck.com/svg/share.svg)">to be used as source</li> <li data-src="http://bhuck.com/svg/stack.svg" style="list-style-image: url(http://bhuck.com/svg/stack.svg)">when hovered over</li> </ul> </div> <div class="appear"> <h2>Div to have images appear on</h2> <img src="http://bhuck.com/svg/share.svg" height="48" width="48"> <p>Willing to use an img element if necessary</p> </div> </body>显示格式化值,请使用this overload

TextBoxFor()

第二个参数是格式字符串。请注意,@Html.TextBoxFor(m => m.MonthlyIncome, "{0:0.00}", new { @class = "form-control"}) 仅在使用DisplayFormatAttributeEditorFor()

时受到尊重

另请注意,DisplayFor()将使用正确的格式呈现值。

答案 1 :(得分:0)

DisplayFormat仅适用于EditorFor/DisplayFor。看看this小提琴为mvc。

<强>模型

使用System; 使用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>