This is because your QuoteQuantity is an int that is currently not Nullable , so when you try to check, the field cannot be empty because it does not allow null s.
2 ways to get around this:
- Set
QuoteQuantity int as int? ( Nullable int )
or
- Use another property to accept the value as
string , and in get for QuoteQuantity use int.TryParse to see if the string can convert to int . You will need some kind of on-site check though to see if it falls within your min / max range - if you have one
An example :
First sentence:
public int? QuoteQuantity { get; set; }
Second sentence: (returns 0 if the string is empty / null or int not valid)
public int QuoteQuantity { get { int qty = 0; if (!string.IsNullOrWhiteSpace(QuoteQuantityAsString)) { int.TryParse(QuoteQuantityAsString, out qty); } return qty; } } public string QuoteQuantityAsString { get; set; }
I would suggest the first option and make sure you do a null check where you use QuoteQuantity :)
Hope this helps!
EDIT:
In the fairness of providing the various options, I just thought of something else (probably better than Proposition 2). In any case, I think Proposition 1 is still the best way.
To return a confirmation only if the user enters something into the input field "Number of quotes" in the view:
View:
In the view, add text input that allows the user to enter a quantity (or not, as may be the case) and use this instead of your current QuoteQuantity elements
Give it id + name something like quoteQty
Add ValidationFor as before, but give it the name quoteQty as the first argument
Controller:
In your POST controller, select another string quoteQty parameter (so this will display the same as name from your view). This will be populated from your HttpPost
Before doing the check (ModelState.IsValid) , try and quoteQty as an int ; if not, add a ModelError for quoteQty , with the message
Then your model will return a validation error and will be displayed on the page as desired.
Downside, this cannot be verified on the client side, so the server will have to return an error
Like this:
public ActionResult SendQuote(Model yourmodel, string quoteQty) { if (!string.IsNullOrWhiteSpace(quoteQty)) { if (!int.TryParse(quoteQty, out yourmodel.QuoteQuantity)) {
And just use the original property
public int QuoteQuantity { get; set; }
in your model. The default int value will be 0 if you never set it. If TryParse fails, it also sets the value to 0
source share