我有一个可以为空的int字段,如下所示。显然这不是一个必填字段。
[DisplayName("Previous Job No:")]
public int? previousJobId { get; set; }
目前,如果用户输入无效,则会显示默认错误消息The field Previous Job No: must be a number.
如何使用数据注释更改此默认错误消息?
谢谢!
答案 0 :(得分:3)
如果您这样做了:
[DataType(DataType.Int32, ErrorMessage = "Custom Error Msg")]
public int? previousJobId { get; set; }
不幸的是,我无法测试此atm。
第二次尝试:
这不是很好,但它将使您不必创建自定义数据注释。反过来,这使您不必编写自定义jQuery验证。我能够测试这个,它对我有用。但是,如果你喜欢这种风格,这取决于你。
[DisplayName("Previous Job No:")]
[RegularExpression("^[0-9]+$", ErrorMessage = "Custom Error Msg")]
public string previousJobId { get; set; }
private int? _previousJobId2;
public int? previousJobId2
{
get
{
if (previousJobId == null)
{
return null;
}
else
{
return Int32.Parse(previousJobId);
}
}
set
{
_previousJobId2 = value;
}
}
您可以在控制器中使用以下方法对其进行测试:
[HttpPost]
public ActionResult Index(HomeViewModel home)
{
if (ModelState.IsValid)
{
int? temp = home.previousJobId2;
}
return View(home);
}
您将在视图中引用该字符串
@Html.LabelFor(model =>model.previousJobId)
答案 1 :(得分:0)
尝试
[Range(1, 1000, ErrorMessage = "Enter a integer value")]
public int? previousJobId { get; set; }
如果可行,请使用外部项目http://dataannotationsextensions.org/Integer/Create