Leo
Leo

Reputation: 495

The spaces inside the URL

I have created the yahoo weather API app using ASP.Net MVC 3 and when I tried to insert the postcode to the text field to find the correct xml, I wanted to leave gap for the standard UK postcode. Can you please help me to do that. The following code's model.PostCode represents the PostCode variable which has declared as string in model. This code is in the controller file.

private Boolean LookupWeather(ref RssModels model)
{    
  string WoeidUrl = "http://where.yahooapis.com/v1/places.q('" +
                     model.PostCode +
                     "')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";

  XDocument getWoeid = XDocument.Load(WoeidUrl);

  try
  {
    model.Woied = (int)(from place in getWoeid.Descendants("place")
                        select place.Element("woeid")).FirstOrDefault();
    return true;
  }
  catch
  {
    return false;
  }

If you can please help me to get the URL like follows. http://where.yahooapis.com/v1/places.q('mk10%202hn')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--

Thank you in advance.

Upvotes: 0

Views: 169

Answers (2)

Jason
Jason

Reputation: 89082

Use UrlEncode

string WoeidUrl = "http://where.yahooapis.com/v1/places.q('" 
    + UrlEncode(postCode)
    + "')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";

Upvotes: 2

Mathew Thompson
Mathew Thompson

Reputation: 56429

All the browser is doing for that is replacing the space with %20, you can replicate this just by using Replace, try:

string postCode = model.PostCode.Replace(" ", "%20");

Then use it in your code above like so:

string WoeidUrl = "http://where.yahooapis.com/v1/places.q('" 
    + postCode
    + "')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";

Upvotes: 1

Related Questions