[英]How can I remove MVC2's validation messages?
我正在使用ASP.NET C#MVC2,我在模型中有以下數據,具有以下數據注釋驗證屬性:
[DisplayName("My Custom Field")]
[Range(long.MinValue, long.MaxValue, ErrorMessage = "The stated My Custom Field value is invalid!")]
public long? MyCustomField{ get; set; }
在該字段中,如果用戶嘗試輸入不能表示為數字的值,則此字段應允許用戶將其留空並顯示驗證消息。 從驗證的角度來看,這是按預期工作並顯示以下錯誤消息:
聲明的我的自定義字段值無效!
“我的自定義字段”字段必須是數字。
第一個驗證消息是我寫的自定義驗證消息,第二個驗證消息是MVC2自動生成的消息。 我需要擺脫第二個,因為它是多余的。 我該怎么做呢? 在我看來,我有以下標記
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
{ %>
<%:Html.ValidationSummary(false)%>
<% Html.ValidateFor(m => m.MyCustomField); %>
這里遇到的問題是因為綁定的屬性是數字,模型綁定會自動處理字符串無法轉換為數字的事實。 這不是RangeAttribute
所做的。
您可以考慮將新屬性作為string
並派生自己的RangeAttribute
,它在字符串級別工作,首先解析數字。
然后你有你的現有屬性換行字符串:
[DisplayName("My Custom Field")]
[MyCustomRangeAttribute(/* blah */)] //<-- the new range attribute you write
public string MyCustomFieldString
{
get; set;
}
public int? MyCustomField
{
get
{
if(string.IsNullOrWhiteSpace(MyCustomField))
return null;
int result;
if(int.TryParse(MyCustomField, out result))
return result;
return null;
}
set
{
MyCustomFieldString = value != null ? value.Value.ToString() : null;
}
}
你的代碼可以繼續在int?
上工作int?
屬性非常愉快,但是 - 所有模型綁定都是在string屬性上完成的。
您還可以理想地將[Bind(Exclude"MyCustomField")]
到模型類型中 - 以確保MVC不會嘗試綁定int?
領域。 或者你可以把它變成internal
。 如果它在Web項目中,您只需要在Web項目中引用它。
您還可以考慮真正的hacky方法 - 並通過ModelState.Errors
在控制器方法中找到該錯誤並在返回視圖結果之前將其刪除...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.