0

我正在編碼一個MVC 5互聯網應用程序,我有一個問題關於視圖模型中的字段驗證。MVC 5模型驗證消息不正確顯示

這裏是我的視圖模型場:

[Display(Name = "Latitude")] 
[Required(ErrorMessage = "Please enter a valid latitude.")] 
public double startupLatitude { get; set; } 

這裏是我的視圖代碼:

<div class="form-group"> 
    @Html.LabelFor(model => model.startupLatitude, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EditorFor(model => model.startupLatitude, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(model => model.startupLatitude, "" , new { @class = "text-danger" }) 
    </div> 
</div> 

如果我輸入的值是不是雙,如下列:

測試

我在視圖中顯示以下驗證消息:

「測試」值對於「緯度」無效。

相反的:

請輸入一個有效的緯度。

這是爲什麼?

在此先感謝。

+0

添加'@ Html.EditorFor()'方法生成的html – 2014-12-03 06:26:41

+0

此行爲是正常且有效的,因爲您正在輸入字符串,而模型屬性的類型爲double。 – 2014-12-03 06:27:40

+0

而'Required'的使用在這裏沒有意義,因爲'double'必須總是有一個值。只有當你有'double?'(可爲空) – 2014-12-03 06:31:39

回答

1

,因爲所需的參數檢查不空,您輸入的數據是「字符串」裏,因爲它預計雙

如果將保持該字段爲空,則錯誤信息將顯示爲「請輸入有效的緯度「。

編輯:

Set Default/Replace Default Validation Message

或者

嘗試使用Regular Expression爲好。

+0

我可以用某種方式修改代碼,以便驗證消息對於空條目或字符串都是相同的嗎? – user3736648 2014-12-03 06:32:03

+0

yes ofcourse您可以等待編輯我的答案 – 2014-12-03 06:32:58

+1

'DataType'不包含'Double'的枚舉值 – 2014-12-03 06:50:07