このサイトは、MVC と DataAnnotations を理解するのに非常に役立ちました。では、質問に移ります。
まず、いくつかの事実: 私は MVC2 と .NET 4.0 フレームワークを使用しています。現在、MVC3 への更新は私にとって選択肢ではありません (これは、私が遭遇した問題の半分に対する最も一般的な答えですが、ここでは実際には問題にならないかもしれません)。
文字列がデータベースの結果セットに既に存在するかどうかを確認するために、完全に機能するカスタム属性を作成しました。クライアント側のメタデータを出力するために、一致するカスタム バリデータと JavaScript も作成しましたが、これも機能します。
私が解決したいのは、バリデータではなくjquery/javascriptを介してクライアントが使用しているエラーメッセージをオーバーライドする方法です。入力フィールドが無効な場合、クライアント側のエラー メッセージに入力フィールドの値を含めたいのですが、これはバリデータでは実行できません。したがって、いくつかのコード:
バリデーター:
public class UniqueStringValidator : DataAnnotationsModelValidator<UniqueStringAttribute>
{
public UniqueStringValidator(ModelMetadata metadata, ControllerContext controllerContext,
UniqueStringAttribute attribute)
: base(metadata, controllerContext, attribute)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
//declare the services we'll need
var rule = new ModelClientValidationRule
{
ValidationType = "uniquestring",
ErrorMessage = "The string is not unique.", //I want to override this on the client, but NOT HERE
};
//This is how I pull additional attributes from the viewmodel in MVC2 (wish I was on MVC3)
//"c" represents the current record we're editing, if we're editing
if (HttpContext.Current.Request.QueryString["c"] != null)
{
int id = Convert.ToInt32(HttpContext.Current.Request["c"]);
string[] stringNames = //call a service and add some query to remove the current record from the results
//and return only the column of strings we're interested in
rule.ValidationParameters.Add("stringlist", stringNames);
}
else
//If we're here, we're not editing an existing record
{
string[] stringNames = //call a service and query only the column of interest
rule.ValidationParameters.Add("stringlist", stringNames);
}
return new[] { rule };
}
}
これが私のJavaScriptバリデーターです:
jQuery.validator.addMethod("uniquestring", function (value, element, params) {
var stringNames = params.stringlist;
for (var i = 0; i < stringNames .length; i++) {
if (value == stringNames [i]) {
//I want to override the error message here so I can include value
return false;
}
}
return true;
});
私はこれを少し再訪し、何が起こっているのかを本当に理解するためにさらにいくつかのことを試みました. エラーメッセージはページの下部にあるメタデータに設定されており、JavaScript 関数で実行できるのは、検証が成功するか失敗するかを判断することだけです。jqueryを使用して関数の最後にエラーメッセージを追加したり、エラーメッセージ要素をjavascriptのテキストに設定しようとしても、違いがないように見えたり、スクリプトが壊れたりすることはありません(後者のアプローチは「機能する」と思われますが、メタデータによってすぐに上書きされます)。
助言がありますか?