7

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,

2 Answers 2

3

Did you try making the Owner int a nullable value?

[Range(0, 255)]
public int? Owner { get; set; }
Sign up to request clarification or add additional context in comments.

1 Comment

this is not working for me - maybe the Range attribute is required?
0

You could check if it's null before checking modelState:

if (viewModel.Owner == null)
{
  viewModel.Owner = 0;
}

if(ModelState.IsValid)
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.