why must I change each int/money column in Models to Nullable: True ?

Last post 07-05-2009 3:29 PM by bradwils. 15 replies.

Sort Posts:

  • why must I change each int/money column in Models to Nullable: True ?

    07-04-2009, 10:15 AM
    • Member
      46 point Member
    • zielony
    • Member since 06-24-2009, 6:22 AM
    • Posts 164

    Why in ASP.NET MVC and linq to sql I must change each int/money column in Models on Nullable: True - otherwise if I in form stay this field empty I get error: "A value is required." + mine communicate of error.

  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-04-2009, 3:37 PM
    • Contributor
      5,577 point Contributor
    • gerrylowry
    • Member since 07-03-2008, 1:46 AM
    • alliston ontario canada
    • Posts 2,087

    In ASP.NET MVC, a lot gets done automatically; sometimes too little, sometimes too much.

    In your Controller, there are various cheats you can use.

    Example:  assume that expiryDate is a database column that can not be null.
    You do not want to force your end user to enter expiryDate.  In your Controller,
    you could check whether expiry date is null, something like:

       if (formData.expiryDate == null) formData.expiryDate = DateTime.Now + 30;

    As long as you do this kludge before you apply changes, you will be safe AFAIK and you will not have to worry about having nulls in your physical database.

     

    Regards,
    Gerry (Lowry)

    Gerry Lowry, Principal
    Ability Business Computer Services ~~ Because it's your Business, our Experience Counts!
    68 John W. Taylor Avenue
    Alliston · Ontario · Canada · L9R 0E1 · gerry.lowry@abilitybusinesscomputerservices.com

    Websites:
    http://abilitybusinesscomputerservices.com
    http://gerrylowryprogrammer.com ~~ résumé & testimonials
    http://veganoccasions.com ~~ recipes
  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-04-2009, 4:29 PM
    • Contributor
      4,300 point Contributor
    • levib
    • Member since 07-23-2007, 11:50 PM
    • Redmond, WA
    • Posts 763
    • AspNetTeam

    zielony:
    Why in ASP.NET MVC and linq to sql I must change each int/money column in Models on Nullable: True - otherwise if I in form stay this field empty I get error: "A value is required." + mine communicate of error.

    Empty form fields represent null values - they can't be converted to any useful data type line int, decimal, etc.  If you try submitting a form with an empty field, the binder will try assigning null to that property.  And if the property is non-nullable, the setter will fail, and the binder will propagate the error back up to the user.

    You have a few options for this.  If you really want the properties to be able to contain empty values, you can make them nullable and the framework will allow empty values to go through.  (It will still fail if you type something truly invalid, e.g. the phrase "dog" for a numeric property.)  If you don't want the binder to handle these properties at all, don't render form input elements for them.  It really depends on what you want to be able to store in your backend.

  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 1:54 AM
    • Member
      46 point Member
    • zielony
    • Member since 06-24-2009, 6:22 AM
    • Posts 164

    gerrylowry the problem is that in visual studio 2010 beta1 + .net 4.0 + MVC 1.1

    I have in database table books with column price which can't be null.

    I can write:

    [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Create([Bind(Exclude = "id_book")] books book)
            {
                if (book.price == null)
                {
                    ModelState.AddModelError("price", "You must write price.");
                }
                if (!ModelState.IsValid) return View(book);
    
    ..................
    
    }



    But when user stays field with price empty he gets error: "A value is required." (not mine error).

    I must change in Model this table column "Nullable" from False on True. Then user gets mine error: "You must write price.".

    I understand why but now I must change this property for each column which is number and isn't Primary Key or ForeignKey in Model. It isn't comfortable :)

  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 3:59 AM
    • Contributor
      5,577 point Contributor
    • gerrylowry
    • Member since 07-03-2008, 1:46 AM
    • alliston ontario canada
    • Posts 2,087

    zielony, it's a flow control issue.  I can not remember the exact sequence ...

    I am assuming that you are creating a new book.

    ModelState.IsValid is a read only property.  If someone else sets it for you to invalid, you are out of luck.

    Line 6 of your example code.  ModelState.AddModelError will also set ModelState.IsValid to false.

    Have you read these tutorials at http://www.asp.net/learn/mvc/?:

    #18 | Performing Simple Validation View in VB or C# 
    #19 | Validating with the IDataErrorInfo Interface View in VB or C#
    #20 | Validating with a Service Layer View in VB or C#
    #21 | Validation with the Data Annotation Validators View in VB or C#

    #21 is the newest of these tutorials.  You'll find different approaches in each tutorial.

    #19 has an interesting comment:
    "DateReleased value is validated automatically. Because the DateReleased property does not accept NULL values, the DefaultModelBinder generates a validation error for this property automatically when it does not have a value. If you want to modify the error message for the DateReleased property then you need to create a custom model binder."

    You may find help here:
    http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx

    #18 talks about "Prebinding Validation and Postbinding Validation":
           "There are actually two types of validation error messages – those generated before the HTML form fields are bound to a class and those generated after the form fields are bound to the class."

    http://odetocode.com/Blogs/scott/archive/2009/04/27/12788.aspx
    "6 Tips for ASP.NET MVC Model Binding"
    http://odetocode.com/Blogs/scott/archive/2009/05/05/12801.aspx
    "Iterating on an ASP.NET MVC Model Binder"

    http://msdn.microsoft.com/en-us/magazine/dd942838.aspx
    "Building Testable ASP.NET MVC Applications"

    http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/03/17/a-better-model-binder.aspx

    http://stephenwalther.com/blog/archive/2009/02/25/asp.net-mvc-tip-49-use-the-linqbinarymodelbinder-in-your.aspx

    For more links, use Google:        asp.net mvc custom model binder

    Regards,
    Gerry (Lowry)

    P.S.:

    Interesting is:  http://www.codeplex.com/FluentValidation
    and http://fluentvalidation.codeplex.com/Wiki/View.aspx?title=mvc
           "Integration with ASP.NET MVC"

    Gerry Lowry, Principal
    Ability Business Computer Services ~~ Because it's your Business, our Experience Counts!
    68 John W. Taylor Avenue
    Alliston · Ontario · Canada · L9R 0E1 · gerry.lowry@abilitybusinesscomputerservices.com

    Websites:
    http://abilitybusinesscomputerservices.com
    http://gerrylowryprogrammer.com ~~ résumé & testimonials
    http://veganoccasions.com ~~ recipes
  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 4:18 AM
    • Member
      46 point Member
    • zielony
    • Member since 06-24-2009, 6:22 AM
    • Posts 164

    But is it possible to change this error in Controller without creating partial class and using there IDataErrorInfo ? I would like to change this errorn in my "if()"

  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 4:58 AM
    • Contributor
      5,577 point Contributor
    • gerrylowry
    • Member since 07-03-2008, 1:46 AM
    • alliston ontario canada
    • Posts 2,087

    zielony:
    But is it possible to change this error in Controller without creating other class, using IDataErrorInfo ? I would like to change this errorn in my "if()"

    zielony, try this:  set a break point at the start of your Controller; when your code breaks, before stepping through it, check the value of the read only property ModelState.IsValid.  If ModelState.IsValid is false before your Controller begins execution, then you will likely have to use some form of custom approach or change your schema to allow nulls (which is a bad idea imo because your database schema rules are your last line of defense against garbage in/garbage out a.k.a. GIGO).

     

    Regards,
    Gerry (Lowry)

    Gerry Lowry, Principal
    Ability Business Computer Services ~~ Because it's your Business, our Experience Counts!
    68 John W. Taylor Avenue
    Alliston · Ontario · Canada · L9R 0E1 · gerry.lowry@abilitybusinesscomputerservices.com

    Websites:
    http://abilitybusinesscomputerservices.com
    http://gerrylowryprogrammer.com ~~ résumé & testimonials
    http://veganoccasions.com ~~ recipes
  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 5:56 AM
    • Member
      46 point Member
    • zielony
    • Member since 06-24-2009, 6:22 AM
    • Posts 164

    ok - I think I will try use Data Annotation Model Binder. But on this site: http://www.asp.net/learn/mvc/tutorial-39-cs.aspx I see that I must select both the Microsoft.Web.Mvc.DataAnnotations.dll assembly and the System.ComponentModel.DataAnnotations.dll from downloaded folder but in this folder there isn't Microsoft.Web.Mvc.DataAnnotations.dll ....

  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 9:26 AM
    • Contributor
      5,577 point Contributor
    • gerrylowry
    • Member since 07-03-2008, 1:46 AM
    • alliston ontario canada
    • Posts 2,087

    That could be overkill.  I do not know.  I have not used it myself.  I am not sure but I think it may only be an alpha (CTP) or Beta at this time.  That's why I prefer to stick within ASP.NET MVC v1.0 which is a finished product and is supported by Microsoft.

    I suggest you might be better off keeping your application as simple as possible and then when it is working to your satisfaction, think about refactoring various parts of it.

    That is one of the selling points of ASP.NET MVC.  If you create your application correctly, you can unplug parts and plug in replacement parts and in theory it should still work and remain robust.

    g.

    Gerry Lowry, Principal
    Ability Business Computer Services ~~ Because it's your Business, our Experience Counts!
    68 John W. Taylor Avenue
    Alliston · Ontario · Canada · L9R 0E1 · gerry.lowry@abilitybusinesscomputerservices.com

    Websites:
    http://abilitybusinesscomputerservices.com
    http://gerrylowryprogrammer.com ~~ résumé & testimonials
    http://veganoccasions.com ~~ recipes
  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 9:45 AM
    • Member
      46 point Member
    • zielony
    • Member since 06-24-2009, 6:22 AM
    • Posts 164

    So as I understand I have 3. options:

    1. Make numeric columns in Models - Nullable: True

    2. Validating with the IErrorDataInfo Interface http://www.asp.net/learn/mvc/tutorial-37-cs.aspx and http://www.asp.net/learn/mvc/tutorial-38-cs.aspx

    3. Validating with Data Annotation Validators http://www.asp.net/learn/mvc/tutorial-39-cs.aspx

    I don't like 2. idea - I have never seen so complicated validation. 3. idea  - no System.ComponentModel.DataAnnotations.dll in files which I downloaded so I can't use it.

    So I must use 1. idea which is stupid but simply.


  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 11:21 AM
    • Member
      46 point Member
    • zielony
    • Member since 06-24-2009, 6:22 AM
    • Posts 164

    I have a suggestion to people from Microsoft who create ASP.NET MVC - please give us possibility easy changing default communicate "A value is required." for empty numeric fields which are required inside controller without using Validating with the IErrorDataInfo Interface / Validating with Data Annotation Validators.

    I am not only person who have this problem - see:

    http://www.google.pl/search?hl=pl&q=asp.net+mvc+%22A+value+is+required.%22&btnG=Szukaj&lr=

    For example in Symfony framework (Symfony and Zend frameworks are the most popular frameworks for php language) we also have default error communicates - BUT WE CAN SIMPLY CHENGE THEM. In ASP.NET MVC it is really too complate - please do somathing with this.

  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 12:30 PM
    • Participant
      1,826 point Participant
    • bradwils
    • Member since 05-19-2008, 1:08 PM
    • Redmond, WA
    • Posts 274

    You can work around this today using the DataAnnotationsModelBinder sample (by using the Required attribute with your own custom message).

    This will be fixed in MVC 2, because it will have DataAnnotations support built-in.

    Senior developer on the ASP.NET MVC team
  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 1:18 PM
    • Member
      46 point Member
    • zielony
    • Member since 06-24-2009, 6:22 AM
    • Posts 164

    good - maybe validation will be easier in mvc 2 :)

    Could You tell me also how I can install DataAnnotationsModelBinder if folder with these files don't have System.ComponentModel.DataAnnotations.dll ?

  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 2:03 PM
    • Contributor
      4,300 point Contributor
    • levib
    • Member since 07-23-2007, 11:50 PM
    • Redmond, WA
    • Posts 763
    • AspNetTeam

    You're overly complicating this issue.  The reason you can't compare that property to null is because the property is non-nullable.  You want to check the user input for 'empty', not the property.

    For example, here's a way to replace our default message:

    if (Request["theField"] == "") {
    ModelState["theField"].Errors.Clear();
    ModelState["theField"].Errors.Add("Your custom error message here.")
    }

    You can also create your own custom model binder for your type.  (In fact, this is exactly why we allow you to do this in the first place.)  This might be overkill for your scenario, however.  You can find samples online for how to do this if you want to go this route.

    Edit: Of course, using the Data Annotations model binder and [Required] will be simpler because it already encapsulates all of this logic.

  • Re: why must I change each int/money column in Models to Nullable: True ?

    07-05-2009, 3:10 PM
    • Member
      46 point Member
    • zielony
    • Member since 06-24-2009, 6:22 AM
    • Posts 164

    ok thx :)

    Other time i will use Data Annotations when somebody add missing .dll :)

Page 1 of 2 (16 items) 1 2 Next >