简体   繁体   中英

If statement doesn't seem to work in a stringbuilder (WebMethod)

I have the following WebMethod that returns a conditional string. Unfortunately the if statement doesn't seem to work. I know that the WebMethod is working because I get the Bla bla bla string but not the icons within the if statement. What am I doing wrong?

[WebMethod]
public static string photos()
{
    StringBuilder photos_sb = new StringBuilder();
    photos_sb.AppendFormat("Bla bla bla bla...");
    db = Database.Open("DefaultConnection"); 
    var HasPhoto = db.Query("SELECT [IDphoto] FROM [photos]");
    if (HasPhoto != null)
    {
        photos_sb.AppendFormat("<img src=\"icon-Green.png\" />");
    }
    else
    {
        photos_sb.AppendFormat("<img src=\"icon-Gray.png\" />");
    }
    db.Close();
    db.Dispose();
    photos_sb.AppendFormat("Bla2 bla2 bla2 bla2...");

    return photos_sb.ToString();
}

Your img tags are missing their closing > . This means that quite possibly they are being outputted but they are not coming out in the format you expected and thus rendering what you expect. The code given will return something like:

Bla bla bla bla...<img src="icon-Gray.png"Bla2 bla2 bla2 bla2...

I would expect a browser to get very confused by this.

If this is in fact a typo and your outputted string really is just "Bla bla bla bla..." then your only possibility would seem to be that you are running the wrong version of your code. IF the above was compiled then it cannot return your value without going through the if statement and running at least one of the branches.

I'd suggest three things:

  1. Ensure you are running the correct compiled code.
  2. Run through it with a debugger to trace its actual execution.
  3. Confirm exactly what your output string is from this method, not what you are seeing several layers of code down the line in whatever is consuming this method.

I think the answer has been provided already so this is just some helpful advice. Save yourself hassle and reduce repeating code:

photos_sb.Append("Bla bla bla bla...");
[....]
photos_sb.Append("<img src=\"");
if (HasPhoto != null)
{
    photos_sb.Append("icon-Green.png");
}
else
{
    photos_sb.Append("icon-Gray.png");
}
photos_sb.Append("\"" />");

This way your condition is only changing the one bit of code that actually varies.

A slightly cleaner way using AppendFormat would be something like this...

photos_sb.AppendFormat("Bla bla bla bla...");
[....]

string photo = "icon-Gray.png";
if (HasPhoto != null)
{
    photo = "icon-Green.png";
}
photos_sb.AppendFormat("<img src=\"{0}\" />", photo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM