2

こんにちは、検証エラー メッセージを (MVC3 で) 変更しようとしており、多くのスレッドを読んで、このスレッドから見つけようとしています。

  • プロジェクトの App_GlobalResources フォルダーを作成します (プロジェクトを右クリック
    -> 追加 -> ASP.NET フォルダーの追加 -> App_GlobalResources)。
  • そのフォルダーに resx ファイルを追加します。MyNewResource.resx と言います。
  • 必要なメッセージ形式でリソース キー PropertyValueInvalid を追加します (たとえば、「コンテンツ {0} はフィールド {1} に対して無効です」)。PropertyValueRequired も変更する場合は、それも追加します。
  • コード DefaultModelBinder.ResourceClassKey = "MyNewResource" を Global.asax スタートアップ コードに追加します。

しかし、私はそれを機能させることはできません。これは、検証メッセージを変更したいクリーンな MVC 3 Web アプリケーションです。私のために、そして他のすべての人のためのサンプルとして、それを機能させてください.

ここに私のテストプロジェクトのリンクがあります

4

1 に答える 1

0

いくつかの検索と試行錯誤の後、このブログ投稿に基づいたコードを使用しました。以下の適応コード。

プロジェクトに新しいクラスを追加します。

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) };
    }
}

app start in を変更して、このアダプターを使用するように 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 をオフにしても、「{} フィールドは必須です」と表示されます。

于 2015-10-14T16:59:39.880 に答える