0

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 !

1
  • If the customer enters a string in the textbox you will always receive null in the Action method. Instead, change the parameter type for a string, and try parsing it to an int Commented Feb 4, 2014 at 20:26

1 Answer 1

1

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.
    }
}
Sign up to request clarification or add additional context in comments.

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.