Question

I have a textbox (not strongly typed) were people can put they're zipcodes (INT) and perform searches off of that. I now want to also enable search functionality of cities (string) from that same textbox is there a way I can do that using the controllers, this is what I had originally with the zipcode functionality

public ActionResult search(int? zipcode)
     {

         // perform zipcode search

    }

that's pretty basic now what I am trying to do is something like this

   public ActionResult search(int? zipcode)
     {

         // The zipcode will be coming to the controller as a "GET"
         // 1.    How can I check if a field is numerical from this controller
        if(zipcode == numerical)
         {
          // perform zipcode search 
       }
       else
       {
         // 2.    obviously this gives me an error cannot implicitly convert string to int
       zipcode = zipcode.ToString();

       // if I can get past those 2 roadblocks then I would search for cities below


    }

    }

My question is how can I allow both cities and zipcodes to be searched in 1 textbox? I have seen multiple websites allow this type of functionality; I am stuck on part 1 and 2 above any suggestions would be great as I am learning more each day !

Was it helpful?

Solution

Treat it as a string by default and try parsing it as an integer. If the parse fails, then it's not a number and you can treat it as a city.

public ActionResult Search(string search)
{
    int zipCode;
    if(int.TryParse(search, out zipCode)
    {
       // It's a zip code and you can use the zipCode variable
    }    
    else
    {
      // Not a number, must be a city. You can use the search variable.
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top