1

ASP.NET MVC プロジェクト用に独自のモデル検証属性を作成しようとしています。この質問のアドバイスに従いましたが@Html.EditorFor()、カスタム属性を認識する方法がわかりません。カスタム属性クラスを web.config のどこかに登録する必要がありますか? この回答に対するコメントは、同じことを求めているようです。

参考までに、私が独自の属性を作成する理由は、Sitecore からフィールドの表示名と検証メッセージを取得したいためであり、各テキストを表す大量の静的メソッドを持つクラスを作成するルートをたどりたくないからです。これは、私が使用する場合に私がしなければならないことです

public class MyModel
{
    [DisplayName("Some Property")]
    [Required(ErrorMessageResourceName="SomeProperty_Required", ErrorMessageResourceType=typeof(MyResourceClass))]
    public string SomeProperty{ get; set; }
}

public class MyResourceClass
{
    public static string SomeProperty_Required
    {
        get { // extract field from sitecore item  }
    }

    //for each new field validator, I would need to add an additional 
    //property to retrieve the corresponding validation message
}
4

1 に答える 1

1

この質問はここで回答されています:

MVC のカスタム検証属性を作成する方法

カスタムバリデーター属性を機能させるには、それを登録する必要があります。これは、次のコードを使用して Global.asax で実行できます。

public void Application_Start()
{
    System.Web.Mvc.DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof (MyNamespace.RequiredAttribute),
        typeof (System.Web.Mvc.RequiredAttributeAdapter));
}

( WebActivatorを使用している場合は、上記のコードをフォルダー内のスタートアップ クラスに入れることができApp_Startます。)

私のカスタム属性クラスは次のようになります。

public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
    private string _propertyName;

    public RequiredAttribute([CallerMemberName] string propertyName = null)
    {
        _propertyName = propertyName;
    }

    public string PropertyName
    {
        get { return _propertyName; }
    }

    private string GetErrorMessage()
    {
        // Get appropriate error message from Sitecore here.
        // This could be of the form "Please specify the {0} field" 
        // where '{0}' gets replaced with the display name for the model field.
    }

    public override string FormatErrorMessage(string name)
    {
        //note that the display name for the field is passed to the 'name' argument
        return string.Format(GetErrorMessage(), name);
    }
}
于 2013-10-30T14:58:24.363 に答える