3

ASP.NET MVC 2モデルの検証にはサブオブジェクトが含まれていますか?

このクラスのインスタンス「Filter」があります。

public class Filter
{
    [StringLength(5)]
    String Text { get; set; }
}

私の主な目的で:

public class MainObject
{
    public Filter filter;
}

ただし、TryValidateModel(mainObject)を実行すると、MainObject.Filter.Textの「Text」が5文字より長くても、検証は機能します。

これは意図されたものですか、それとも私は何か間違ったことをしていますか?

4

1 に答える 1

1

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

于 2010-07-10T06:55:47.520 に答える