loki
loki

Reputation: 2966

How to disable required attributes MVC model?

I have a model :

[Range(1, 24, ErrorMessage = "Invalid Hour")]
public int val1{ get; set; }

[Required(AllowEmptyStrings = true)]
public string val2 { get; set; }

I have a edit action also I have view page. There are 2 textboxes val1.text, val2.text if I write fill view form (I am not writing any value on val1) return InvalidHour. I want to give ability to set empty value (not writing something on val1). PROBLEM on val1 return Invalid Hour when empty! can i give empty?

How to do it?

Upvotes: 0

Views: 726

Answers (2)

Andrew
Andrew

Reputation: 5430

You can make it a nullable int

[Range(1, 24, ErrorMessage = "Invalid Hour")]
public int? val1{ get; set; }

Upvotes: 5

Chandermani
Chandermani

Reputation: 42669

Integer is a primitive data type. Try to make it nullable with int?

Upvotes: 1

Related Questions