2013-08-20 56 views
2

您好我一直在試圖更改驗證錯誤信息(在MVC3),並閱讀了大量的線程和this thread發現:如何更改驗證錯誤消息在MVC

  • 創建文件夾App_GlobalResources文件爲您項目(右擊
    項目 - >添加 - >添加ASP.NET文件夾 - > App_GlobalResources)。
  • 在該文件夾中添加一個resx文件。說MyNewResource.resx。
  • 添加資源鍵PropertyValueInvalid與期望的消息 格式(例如「內容{0}對字段{1}」無效)「)。如果你想 更改PropertyValueRequired也添加它。
  • 將您的Global.asax啓動代碼添加到代碼DefaultModelBinder.ResourceClassKey =「MyNewResource」至 。

但我不能讓它工作。這裏是一個乾淨的MVC 3 Web應用程序,我想更改驗證消息。請讓它爲我工作,併爲其他人提供樣本。

here是鏈接,我的測試項目

+0

看看這個http://stackoverflow.com/questions/6214066/how-to-change-default-validation-error-message-in-asp-net-mvc .. – user2232273

+0

我試過在鏈接,我把「RequiredAttribute_ValidationError」和「PropertyValueRequired」鍵都放在資源文件中,但什麼都沒有發生。 –

+0

請在查詢中粘貼您的模型/視圖/控制器 –

回答

0

一些搜索和反覆試驗之後,我使用了基於this blog post一些代碼。改編下面的代碼。

添加一個新類到您的項目:

using System.Web.Mvc; 
public class FixedRequiredAttributeAdapter : RequiredAttributeAdapter 
{ 
    public FixedRequiredAttributeAdapter (ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute) 
     : base(metadata, context, attribute) 
    { 
    } 

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() 
    { 
     // set the error message here or use a resource file 
     // access the original message with "ErrorMessage" 
     var errorMessage = "Required field!": 
     return new[] { new ModelClientValidationRequiredRule(errorMessage) }; 
    } 
} 

告訴MVC通過改變應用程序開始在global_asax使用該適配器:

protected void Application_Start() 
    { 
     ... 
     DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(
      typeof(RequiredAttribute), 
      (metadata, controllerContext, attribute) => new FixedRequiredAttributeAdapter(
       metadata, 
       controllerContext, 
       (RequiredAttribute)attribute)); 

還有更多,你可以用錯誤消息,因爲這樣做從基於類/屬性的資源文件獲取:

var className = Metadata.ContainerType.Name; 
    var propertyName = Metadata.PropertyName; 
    var key = string.Format("{0}_{1}_required", className, propertyName); 

使用MVC5進行測試。


更新:看起來這僅適用於JavaScript的/不顯眼的驗證。如果您關閉JavaScript以獲得回傳驗證,它仍會顯示「The {}」字段是必需的「。

+0

這在ASP.NET Core中不起作用(不同的方法簽名)。有一些解決方法嗎? – grokky