Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc - optional/default value for integer field

Say I have a viewmodel like so:

public class User 
{
    public int Id { get; set; }

    [Required(ErrorMessage="Username is required")]
    public string Username { get; set; }

    [Range(0, 255)]
    public int Owner { get; set; }
}

The page is submitted to it's controller where I check if ModelState.IsValid, however it doesn't pass. Obviously, owner is required. Why is that? I thought the default value for an unassigned int was 0. If I debug the app and inspect the object that is sent to the controller, the value is indeed 0.

If I don't want to force the user to enter 0, what's the best approach? I've tried adding a [DefaultValue(0)] attribute to the Owner property in the class but it does not seem to do any difference.

Some guidance would be nice even if this is such a newbie or trivial getting-used-to-the-concept kind of problem.

Regards,

like image 775
Adam Asham Avatar asked Feb 22 '11 19:02

Adam Asham


1 Answers

Did you try making the Owner int a nullable value?

[Range(0, 255)]
public int? Owner { get; set; }
like image 183
Leniel Maccaferri Avatar answered Oct 02 '22 21:10

Leniel Maccaferri