7 Gedanken zu „ASP.NET MVC Quick Tip: Check Data Annotations from code“

  1. I’ve implemented this and all my post code still works as before. That’s good, but is there some way to test it? Also, my controllers all inherit from a base controller so perhaps the code is doing nothing.

  2. Of course you can test itby invoking a controller action with model entities you assume. Then you can look if the model state is valid or invalid depending on what you expect to get from your annotated model. Base controller should be no problem if the concrete controller still has the MVC „Controller“ class in the inheritance hierarchy.

  3. Thanks for the prompt response. I’m not sure how to manipulate the model to produce a valid test.

    Assume a single input of „ArticleName“ — — 35 varchar in database,
    and
    field input of

    Html.TextBoxFor(model => model.articleToCreate.ArticleName, new { style = „width: 235px;“ })

    ArticleName has a Required attribute in my Class.

    How could this be tested?

  4. Hi Joe,

    I’m not sure WHAT you want to test. Do you want to test that the model validation is performed and produces an invalid ModelState when the ArticleName is null/empty? Of course your test has to invoke the according controller action with the invalid model entity. Afterwards you can check if the ModelState was invalid (thus the model validation was performed correctly). I hope you know how to test MVC controllers, else there are some great articles on the web.

  5. If ArticleName does not allow NULL in db and the Required attribute is removed from the Class, then validation still returns an error message on the form when submitted. The error returned is:
    The value “ is invalid.
    However, this happens with or without using your code above.

    If ArticleName allows NULL then the item is added to db with a null value, and that can cause major problems unless SELECT commands include a ISNULL value.

    As to what I want to test, it is to test something live in a way some malicious user might do so as to see what the code you provided does.

    At any rate, I don’t want to impose on your time and thanks for your replies.

  6. Your entire last section is wholly unnecessary (as far back as early February with MVC2 RC2). You state: „That means only the Data Annotations on the posted form values are checked, but not other properties which are perhaps defined on the model class, but missing in the form values.“

    But MVC2 Data Annotation Validation now does Model Validation not Input Validation. Check out http://weblogs.asp.net/scottgu/archive/2010/02/05/asp-net-mvc-2-release-candidate-2-now-available.aspx

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.