0

I'm having issues with one of the pages on my site where I'm using a cookie value to pull some data out of my DB. It's working fine for my strings, but having issues with my integers and dates.

I start by declaring blank variables:

int numAdults;

I then check to see if a cookie is set, and if it is, I perform a database query (numAdults is data type int in the DB):

if(Request.Cookies["BookingReq"] != null){
    var breq = db.QuerySingle("SELECT * FROM BookingRequests WHERE BookingGUID = @0", Request.Cookies["BookingReq"].Value);  
    numAdults = int.Parse(breq.NumAdults);        
}

The, in my form, I want to show as empty if the cookie isn't set, or show the "selected" option if it is:

<select class="form-control" id="numAdults" name="numAdults" @Validation.For("numAdults")>
    <option>Choose</option>
    <option value="0" selected="@(int.Parse(numAdults) == 0)">0</option>
    <option value="1" selected="@(int.Parse(numAdults) == 1)">1</option>
    <option value="2" selected="@(int.Parse(numAdults) == 2)">2</option>
    <option value="3" selected="@(int.Parse(numAdults) == 3)">3</option>
    <option value="4" selected="@(int.Parse(numAdults) == 4)">4</option>
</select>

This, however, leaves me with the following error when I run the page:

<option value="0" selected="@(numAdults == 0)">0</option>
Operator '==' cannot be applied to operands of type 'string' and 'int'
3
  • 1
    numAdults is a string, not an int.
    – Joe Enos
    Apr 7, 2015 at 19:16
  • I've got a feeling i need to add an AsInt() in there somewhere, but i'm not sure where?
    – Gavin5511
    Apr 7, 2015 at 19:17
  • 1
    @(int.parse(numAdults) == 0)
    – ro-E
    Apr 7, 2015 at 19:17

1 Answer 1

1

Not sure how WebMatrix is returning its dynamic result, but I think breq.NumAdults must actually be a string, otherwise it should error out when assigning to numAdults. (Confirm this by throwing a breakpoint on that line and inspecting breq.NumAdults).

It seems what you want to do is make numAdults an integer, then parse when retrieving from the database:

int numAdults; // Or pre-set this to zero if you need a default value.
...
numAdults = int.Parse(breq.NumAdults);
2
  • I'm not getting this error "<option value="0" selected="@(int.Parse(numAdults) == 0)">0</option>" --- The best overloaded method match for 'int.Parse(string)' has some invalid arguments
    – Gavin5511
    Apr 7, 2015 at 19:26
  • Once your numAdults variable is an integer, then your original @(numAdults == 0) is fine, and you don't need the parse there.
    – Joe Enos
    Apr 7, 2015 at 19:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.