2

I'm going straight to the point here.

I'm trying to display the Monthly Income to have 2 decimal only.

I've tried using DisplayFormat however it doesn't work when I add it on Textbox.

Model

public class AgentModel
{

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

View

//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"})

I'm confused what is the difference between the two inputs. I'm using the DataFormat because I want the format to be centralized on my model. and to not use this code @string.Format("{0:N2}",decimal.Round(agent.MonthlyIncome, 2, MidpointRounding.AwayFromZero)) to limit the decimal places. since I'll be doing this in all of my views if this is what I do.

I've also tried to just output the value of monthly income

<td>@agent.MonthlyIncome</td>

this still returns 5 decimal places.

2 Answers 2

6

To display a formatted value using TextBoxFor(), use this overload

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

The 2nd parameter is the format string. Note that the DisplayFormatAttribute is only respected when using EditorFor() or DisplayFor()

Note also that <td>@Html.DisplayFor(m => m.MonthlyIncome)</td> will render the value with the correct format.

Sign up to request clarification or add additional context in comments.

6 Comments

I see..., so I need to add the format parameter on every views that I have? where as if I use the EditorFor it'll automatically add the dataanotation on my model..
If you want to use TextBoxFor(), then yes. But is there a reason you do not want to use EditorFor() - the 2 implementations in your question will generate identical html.
Hi steph.. I'm going to use EditorFor since it is efficient when it comes to editing the format of the textbox.... however, how can I display the format of the MonthlyIncome if I tried to add this on my table liek this <td>@agent.MonthlyIncome</td> coz it will still display 5 decimal places unlike when usingEditorFor it'll convert it to textbox and convert the display?
See the last paragraph of my answer
how about when I loop the data... and I got a bunch of monthlyIncome?
|
0

DisplayFormat only works with EditorFor/DisplayFor. Look at this fiddle for mvc.

Model

using System; using 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; }
    }
}

Controller

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"} ;
    }
}

View

@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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.