我有一个非常相似的问题,并通过在我的 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(".", "");
}
}
}