0

我的数据库中存储了一个字符串,该字符串始终为 12 个字符(数字)长。我希望它在屏幕上显示为:“###/####/####”

我喜欢使用 DisplayFormatAttribute

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

但提供的 DataFormatString 似乎不起作用。

编辑我通过创建客户 DisplayFormatAttribute 来解决这个问题,但这似乎并不那么明显。

有什么建议么 ?

4

1 回答 1

0

我有一个非常相似的问题,并通过在我的 viewmodel 类中使用 UIHint 属性来解决它。此外,我随后在我的 EditorTemplates 文件夹中创建了一个格式化程序。(我认为 MVC 默认会查找该文件夹)。所以发生的事情是渲染引擎用格式化程序替换了我认为的编辑器。我的示例是 11 位数的银行帐号,因此您必须针对您的情况稍微修改它。后端数据库只接受没有分隔符的 11 位数字,因此我在保存之前删除了这些数字。

在我看来

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

在文件夹 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" />

视图模型

private string _BankAccount;
[UIHint("_BankAccountFormatter")]
public string BankAccount
{
  get
  {
    return _BankAccount;
  }
  set
  {
    if (!String.IsNullOrEmpty(value))
    {
      _BankAccount = value;
      _BankAccount = _BankAccount.Trim();
      _BankAccount = _BankAccount.Replace(".", "");
    }
  }
}
于 2015-09-09T11:45:08.763 回答