2つの意見:
- モデルのフィールドではなく、パブリックプロパティを使用する
- 検証しようとしているインスタンスは、これが機能するためにモデルバインダーを通過する必要があります
最初の発言はあまり説明する必要はないと思います。
public class Filter
{
[StringLength(5)]
public String Text { get; set; }
}
public class MainObject
{
public Filter Filter { get; set; }
}
2つ目は、機能しない場合です。
public ActionResult Index()
{
// Here the instantiation of the model didn't go through the model binder
MainObject mo = GoFetchMainObjectSomewhere();
bool isValid = TryValidateModel(mo); // This will always be true
return View();
}
そして、これがいつ機能するかです:
public ActionResult Index(MainObject mo)
{
bool isValid = TryValidateModel(mo);
return View();
}
もちろん、この場合、コードは次のように簡略化できます。
public ActionResult Index(MainObject mo)
{
bool isValid = ModelState.IsValid;
return View();
}
結論:必要になることはめったにありませんTryValidateModel
。