簡體   English   中英

MVC DisplayFormatAttribute-字符串的DataFormatString

[英]MVC DisplayFormatAttribute - DataFormatString for strings

我的數據庫中存儲的字符串始終長12個字符(數字)。 我希望它在屏幕上顯示為:“ ### / ##### / ####”

我喜歡使用DisplayFormatAttribute

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

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

編輯我通過創建客戶DisplayFormatAttribute來解決此問題,但這似乎並不那么明顯。

有什么建議么 ?

我有一個非常類似的問題,並通過在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(".", "");
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM