MVC DisplayFormatAttribute - DataFormatString for strings

142 Views Asked by At

I have a string stored in my DB that is always 12 characters (digits) long. I want it to be displayed on screen as : "###/####/####"

I like to use a DisplayFormatAttribute

[DisplayFormat(DataFormatString = "{0:##/####/#####}", ApplyFormatInEditMode = true)]

But the provided DataFormatString does not seems to be working.

EDIT I tought solving this by creating a customer DisplayFormatAttribute, but this seems not to be that obvious.

Any suggestions ?

1

There are 1 best solutions below

0
Hallgeir Engen On

I had a quite similar problem, and solved it by using the UIHint attribute in my viewmodel class. In addition I then created a formatter in my EditorTemplates folder. (MVC looks for that folder by default i think). So what happens is that the rendring engine replace the editor in my view with the formatter. My example is for bankaccount number with 11 digits, so you have to modify it slightly for your case. The backend db only accept 11 digits with no separators, so therefore i remove these before i save.

In my view

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

In folder Views/EditorTemplates

@model String

@{
    Script.Require("common");
}

@{String temp = String.Empty;}

@if (!String.IsNullOrEmpty(Model))
{
    if (Model.Length == 11)
    {
        temp = String.Format("{0: ####-##-##-###}", Convert.ToInt64(Model)).Replace("-",".");
    }
    else
    {
        temp = Model;
    }
}

<input type="text" id="BankAccount" name="BankAccount" class="form-control span6" onkeypress="NumberFilter(event, '.');" value="@temp" />

ViewModel

private string _BankAccount;
[UIHint("_BankAccountFormatter")]
public string BankAccount
{
  get
  {
    return _BankAccount;
  }
  set
  {
    if (!String.IsNullOrEmpty(value))
    {
      _BankAccount = value;
      _BankAccount = _BankAccount.Trim();
      _BankAccount = _BankAccount.Replace(".", "");
    }
  }
}