[Required]
カスタムの型付きプロパティに貼り付けるときに、属性のルールを「カスタマイズ」する方法がわかりません。コードは次のようになります。
public class MyProp
{
public Guid Id {get;set;}
public string Target {get;set;}
}
public class MyType : IValidatableObject
{
public string Name {get;set;}
public MyProp Value {get;set;}
private MyType()
{
this.Name = string.Empty;
this.Value = new MyProp { Id = Guid.Empty, Target = string.Empty };
}
public MyType(Guid id) : this()
{
this.Value.Id = id;
// Fill rest of data through magic
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(this.Value.Id == Guid.Empty)
yield return new ValidationResult("You must fill the property");
}
}
このモデルは、リストからの選択を可能にするボタン付きのテキスト ボックスとして (独自の を介してEditorTemplate
) フォームに表示されます (バッキング データは Dynamics CRM 2011 環境であり、このモデルは実際にはルックアップ属性を表すことを目的としています)。
public class MyModel
{
// Many props
[Required] // This one is enforced correctly
public string MyString {get;set;}
[Required] // This one isn't
public MyType MyData {get;set;}
public MyModel() { this.MyData = new MyType(); }
}
結果のビューにはフィールドが表示されます (もちろん空です)。ユーザーは、フィールドをクリックしてリストから選択することによってのみデータを入力できます (jquery ダイアログがこれを処理し、既に機能しています)。
インターフェイスはIValidatableObject
有望に思えますが、コードが呼び出されることはないようです。
コントローラーでは、私は単にやっています
[HttpPost]
public ActionResult MyAction(FormCollection data)
{
if (!ModelState.IsValid) return View();
// magic: handle data
}
何が欠けていますか?おそらくIValidatableObject
インターフェイスの使用法を誤解しましたか?