DisplayFormat for TextBoxFor in MVC

64,116

Solution 1

You should use Html.EditorFor instead of Html.TextBoxFor if you want the custom format to be taken into account:

@Html.EditorFor(m => m.TotalAmount)

Also make sure that you have set ApplyFormatInEditMode to true:

[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }

The DisplayFormat attribute is intended to be used only with templated helpers such as EditorFor and DisplayFor. This is the recommended approach instead of using TextBoxFor.

Solution 2

This works in MVC5

@Html.TextBoxFor(m => m.TotalAmount, "{0:0.00}")

Solution 3

Try like this:

@{
     var format = String.Format("{0:0.00}", Model.TotalAmount);
}
@Html.TextBoxFor(m => m.TotalAmount, format)

Hope it helps.

Solution 4

If you need more control of the field being displayed (vs. a built in EditorFor template) create a custom EditorFor template yourself. Inside an EditorFor template, the built in Html Helpers like @Html.TextBox() can be used with automatic client side validation and Display attributes which are usually only available to EditorFor and DisplayFor.

For example looping through a List of items. The input name has to have an unbroken index.

// Optional, if you require a custom input name for binding
String fieldName = String.Format("FieldNameForBinding[{0}].Property", index)

@Html.EditorFor(m => m.Property, "MyCustomEditorTemplate", fieldName)

Then you can setup your model

[CustomValidation(..optional..)]
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }

The EditorFor template (in e.g. ~/Views/Shared/EditorFor/MyCustomEditorTemplate.cshtml) Note the name is left empty, it comes from the fieldName automatically. You can see it in the ViewData.TemplateInfo.HtmlFieldPrefix. Now you have complete control over the display of the field.

@model object
@{
    Decimal? actualValue = (Decimal?)Model;
}
// The TextBox and ValidationMessage "names" are empty, they are filled   
// from the htmlFieldName given via the @Html.EditorFor() call.
@Html.TextBox("", actualValue, new { @class = "cssClass" })
@Html.ValidationMessage("")

The idea is that you can customize the input field however you would like, and use e.g. @Html.TextBox() which outside of a custom EditorFor template would not utilize the built in client-side validation. You don't need to use the custom naming of the input field, that was simply an example of the usefulness of this solution. You can customize the way the data is presented (CSS, etc.) instead of relying on the built in EditorFor templates.

Solution 5

I solve that issue in this way:

@Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)

or create next extension:

public static class HtmlExtensions
{
    public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        return htmlHelper.TextBoxFor(expression, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).EditFormatString, htmlAttributes);
    }
}

But you need to set ApplyFormatInEditMode=true in DisplayFormatAttribute on your field.

Share:
64,116

Related videos on Youtube

Murali Murugesan
Author by

Murali Murugesan

Working as a Senior FullStack &amp; Cloud Developer in Stockholm, Sweden. Interested in Web stack, Application Architecture and Design, Front end development frameworks. C# Azure ASP.NET Core Angular TypeScript WebAPI micro-services Agile Domain Driven Design Clean Code TDD SQL Server Clean Coder, Passionate to build a better software!

Updated on August 04, 2022

Comments

  • Murali Murugesan
    Murali Murugesan almost 2 years

    I need to round off 4 digit decimal to 2 digits and show in MVC 3 UI

    Something like this 58.8964 to 58.90

    Tried following this How should I use EditorFor() in MVC for a currency/money type? but not working.

    As i am using TextBoxFor=> i removed ApplyFormatInEditMode here. Even i tried with ApplyFormatInEditMode , but nothing works. Still showing me 58.8964.

    MyModelClass

     [DisplayFormat(DataFormatString = "{0:F2}")]
     public decimal? TotalAmount { get; set; }
    
     @Html.TextBoxFor(m=>m.TotalAmount)
    

    How can i achieve this round off?

    I can't use EditorFor(m=>m.TotalAmount) here, as i need to pass some htmlAttributes

    Edit:

    After debugging with MVC source code, they internally use

     string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
    

    in MvcHtmlString InputHelper() method of InputExtension.cs that takes object value as parameter and converting. They are not using any display format there. How could we fix?

    I managed to fix in this way. As i have a custom helper, i can able to manage with the below code

     if (!string.IsNullOrEmpty(modelMetaData.DisplayFormatString))
       {
         string formatString = modelMetaData.DisplayFormatString;
         string formattedValue = String.Format(CultureInfo.CurrentCulture, formatString, modelMetaData.Model);
         string name = ExpressionHelper.GetExpressionText(expression);
         string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
           return htmlHelper.TextBox(fullName, formattedValue, htmlAttributes);
       }
       else
       {
           return htmlHelper.TextBoxFor(expression, htmlAttributes);
       }
    
    • Karthik Chintala
      Karthik Chintala over 11 years
      Try using [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
    • Murali Murugesan
      Murali Murugesan over 11 years
      @Karthik, Sure. But let me try debugging MVC source code and see where it is setting like that
    • Murali Murugesan
      Murali Murugesan over 10 years
      We now allow passing in HTML attributes in EditorFor as an anonymous object from MVC 5.1 update
  • Murali Murugesan
    Murali Murugesan over 11 years
    It is not working. Also you are passing the formatted value to a htmlAttributes parameter
  • Murali Murugesan
    Murali Murugesan over 11 years
    But i need to pass html attributes.
  • Murali Murugesan
    Murali Murugesan over 11 years
    Why MVC team can consider this as fix and implement for next release?
  • Darin Dimitrov
    Darin Dimitrov over 11 years
    Why would the MVC team consider such a thing? I don't think that this is a bug. You should be using templated helpers anyway. Personally I always use Html.EditorFor and never Html.TextBoxFor.
  • Murali Murugesan
    Murali Murugesan over 11 years
    Yes correct. But the EditorFor not accepting htmlAttributes as a parameter. :(
  • Darin Dimitrov
    Darin Dimitrov over 11 years
    But why do you need such parameter? By the way you could write a custom model metadata provider as illustrated in the following blog post: http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-h‌​tml-attributes-suppo‌​rt-for-Templates-_2D‌​00_-ASP.Net-MVC-2.0-‌​Beta_2D00_1.aspx
  • Murali Murugesan
    Murali Murugesan over 11 years
    The form is generated based on the fields defined in the database. Some fields are readonly and some fields are special. So i need to add a class like 'highlight' for special fields and 'readonly' attribute for read only fields. Also the field has a type defined in DB like textbox, dropdown etc. So i created my custom control factory class to generate!
  • Murali Murugesan
    Murali Murugesan over 11 years
    Updatd my previous comment, which has more information on what i need.
  • Murali Murugesan
    Murali Murugesan over 11 years
    That looks really nice. I follow implementing my own custom model metadata provider. Thanks a lot. :)
  • Sinaesthetic
    Sinaesthetic almost 11 years
    Why would I want to add a property? Perhaps for jquery/javascript reasons?
  • Murali Murugesan
    Murali Murugesan over 10 years
    @DarinDimitrov, Great news, We now allow passing in HTML attributes in EditorFor as an anonymous object from MVC 5.1 update
  • Brad
    Brad about 10 years
    i used this approach for a date. i couldn't use EditorFor since it doesn't let you specify classes.
  • QMaster
    QMaster over 7 years
    Great, use this formatter "{0:N0}" if you want to avoid decimal point and Symbols.
  • Okan Kocyigit
    Okan Kocyigit over 6 years
    @DarinDimitrov, is that possible to set invariant culture?