1

我有一个可为空的 int 字段,如下所示。显然,这不是必填字段。

[DisplayName("Previous Job No:")]
public int? previousJobId { get; set; }

目前,如果用户输入无效,则显示默认错误消息The field Previous Job No: must be a number.

如何使用数据注释更改此默认错误消息?

谢谢 !

4

2 回答 2

3

如果你这样做了:

[DataType(DataType.Int32, ErrorMessage = "Custom Error Msg")]
public int? previousJobId { get; set; }

不幸的是,我无法测试这个自动取款机。

第二次尝试:

这并不漂亮,但它可以让您不必创建自定义数据注释。这反过来又使您不必编写自定义 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)
于 2012-06-07T14:05:53.673 回答
0

尝试

[Range(1, 1000, ErrorMessage = "Enter a integer value")]
 public int? previousJobId { get; set; }

或在可行的情况下使用外部项目http://dataannotationsextensions.org/Integer/Create

以下是他们如何实现它:https ://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions/IntegerAttribute.cs

于 2012-06-07T14:10:43.437 回答