1

I have this line of code that forms an html string:

StringBuilder builder = new StringBuilder();
builder.Append("<a href='#' onclick=");
builder.Append((char)22); //builder.Append('\"');
builder.Append("diagnosisSelected('" + obj.Id + "', '" +obj.Name + "')");
builder.Append((char)22);
builder.Append(" >" +  obj.Name + "</a>");

In the browser I get

<a href='#' onclick=\"diagnosisSelected('id', 'text')\" >some text here</a>

and I get an error because of \". How can I output a "?

3
  • 2
    I think part of your trouble is that " has the ASCII value 0x22 (hexadecimal), not 22 (decimal). Commented Dec 28, 2009 at 18:58
  • 1
    What is the value of diagn.Name gives that output? My first guess would be "text", but that doesn't seem consistent with the link text. Are you sure this code is running? Commented Dec 28, 2009 at 18:59
  • The problem was in IE :) Commented Dec 30, 2009 at 15:28

4 Answers 4

11

It's funny how many times I see people use StringBuilder yet completely miss the point of them. There's another method on StringBuilder called AppendFormat which will help you a lot here:

builder.AppendFormat("<a href='#' onclick=\"foo('{0}','{1}')\">{2}</a>", var1, var2, var3);

Hope this helps,

Sign up to request clarification or add additional context in comments.

3 Comments

or @"<a href='#' onclick=""foo('{0}','{1}')"">{2}</a>" if the backslashes look as goofy to you as they do to me.
I'm not a fan of the doubled-up quotes simply because it annoys resharper too much :)
AppendFormat is useful when the goal is to insert formatted string at the end of current "builder" string value, but what to do to insert formatted string at the beginning ? I am using builder.insert(0,str) so in this case how to add str as formatted html string?
5

Use a \"

Quotes are special characters, so they have to be "escaped" by putting a backslash in front of them.

i.e. instead of

builder.Append((char)22); 

use

builder.Append("\""); 

2 Comments

a pass the string as a Json, and the result is still \", and i had the same error when appending \"
In that case it could be that something between building the string and emitting it to the output HTML is 'escaping' the quotes for you. It's probably best if you post the code you're using to output the text so people can try to see where it may be being escaped.
2

Inside of a double quoted string, a \ is an escape character. To insert just a ", you would use "\"".

Comments

1

Replace the following line:

builder.Append((char)22);

with

builder.Append("\"");

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.