Formatting Field Values - ASP.NET MVC

Overview

By default, the Html.TextBoxFor method applies no formatting to field values. This article describes how to easily format the data and still have MVC pickup the changes for the view model.

Solution

The default way of creating the textbox, shown below, doesn't format the field value.

<%: Html.TextBoxFor(m => m.Account.Balance)%>

The following code demonstrates how to format field values within an ASPX page on a site that's using MVC.

<%: Html.TextBox("Account.Balance", 
        String.Format("{0:F2}", Model.Account.Balance), 
        new {   id="Account_Balance", 
                style="width:6em;"} )
        %>