1

私の ASP.NET MVC3 プロジェクトには、このようなビュー モデルがあり、プロパティ用にハード コードされたエラー メッセージがあります。

public class UserProfileVM
{
  [Required]
  [StringLength(200, ErrorMessage = "Name should be 10 chars")]
  public string Name { set;get;}

 //other properties
}

ErrorMessageユーザーのプリファレンス設定 (ユーザーが選択した言語) に基づいて、属性の値を動的にロードしたいと考えています。だから私はこのような言語ラベルを返す関数を持っています

public string GetLabel(string labelCode)
{
  string labelText="Get from somewhere using labelCode";
  //Get User's language preference from Session and return the labelText here
  return labelText;
}

ビューモデルでこのように使用しようとしました

[Required]
[StringLength(200, ErrorMessage = GetLabel("MinCharErr"))]
public string Name { set;get;}

しかし、コードをコンパイルできません。An attribute argument must be a constant expression,typeof expression or array creation expression of an attribute parameter type のようなエラーが表示されます

誰かがそれを修正する方法を教えてもらえますか。メソッドを使用してGetLabel、関連するテキストを取得する必要があります。

4

2 に答える 2

1

StringLengthこれを実装するには、独自のクラスを作成する必要があります。

public class CustomStringLength : StringLengthAttribute {
    public CustomStringLength() {
        //Set your error message right here
        base.ErrorMessage = userOptions.GetErrorByLabel(labelCode);
    }
}

明らかに、これはバックエンド データに接続する必要がありますが、これはエラー メッセージを動的に設定する方法の一般的な考え方です。

于 2013-06-17T21:39:01.140 に答える
0

しかし、コードをコンパイルできません。An attribute argument must be a constant expression,typeof expression or array creation expression of an attribute parameter type のようなエラーが表示されます

プロパティをカスタマイズして動的な結果を取得ErrorMessageResourceNameすることはできないためです。ErrorMessageResourceType

カスタマイズされたクラスでパラメーター化されたコンストラクターを渡すことによってのみ、クラスでLengthプロパティをカスタマイズできます。StringLengthAttributeつまりOverrideLengthString

あなたが言ったように、対応する を取得するためにいくつかのキーを渡したいのですがError Message、それは不可能です。

以下のメッセージをリソースファイルに書き込むこともできます

"Maximum allowed length is {0}"

実行時に、カスタムクラスでパラメーター化されたコンストラクター値 (最大文字列長) で文字列を置き換えることにより、文字列をフォーマットできます。

セッションからユーザーの言語設定を取得し、ここに labelText を返します

Global.asax ファイルで言語を設定しました。そのため、リソース ファイルはUserLanguage. したがって、キー名を指定するだけでResource file、選択した言語に従って対応する値が取得されます

どうすれば言語を設定できますか?

public sealed class LanguageManager
{
    /// <summary>
    /// Default CultureInfo
    /// </summary>
    public static readonly CultureInfo DefaultCulture = new CultureInfo("en-US");

    /// <summary>
    /// Available CultureInfo that according resources can be found
    /// </summary>
    public static readonly CultureInfo[] AvailableCultures;

    static LanguageManager()
    {
        List<string> availableResources = new List<string>();
        string resourcespath = Path.Combine(System.Web.HttpRuntime.AppDomainAppPath, "App_GlobalResources");
        DirectoryInfo dirInfo = new DirectoryInfo(resourcespath);
        foreach (FileInfo fi in dirInfo.GetFiles("*.*.resx", SearchOption.AllDirectories))
        {
            //Take the cultureName from resx filename, will be smt like en-US
            string cultureName = Path.GetFileNameWithoutExtension(fi.Name); //get rid of .resx
            if (cultureName.LastIndexOf(".") == cultureName.Length - 1)
                continue; //doesnt accept format FileName..resx
            cultureName = cultureName.Substring(cultureName.LastIndexOf(".") + 1);
            availableResources.Add(cultureName);
        }

        List<CultureInfo> result = new List<CultureInfo>();
        foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
        {
            //If language file can be found
            if (availableResources.Contains(culture.ToString()))
            {
                result.Add(culture);
            }
        }

        AvailableCultures = result.ToArray();

        CurrentCulture = DefaultCulture;
        if (!result.Contains(DefaultCulture) && result.Count > 0)
        {
            CurrentCulture = result[0];
        }
    }

    /// <summary>
    /// Current selected culture
    /// </summary>
    public static CultureInfo CurrentCulture
    {
        get { return Thread.CurrentThread.CurrentCulture; }
        set
        {
            Thread.CurrentThread.CurrentUICulture = value;
            Thread.CurrentThread.CurrentCulture = value;
        }
    }
}
于 2013-06-18T01:28:09.383 に答える