views:

483

answers:

4

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 "?

+2  A: 

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

Jake Basile
+6  A: 

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("\""); 
Jason Williams
a pass the string as a Json, and the result is still \", and i had the same error when appending \"
CoffeeCode
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.
Jason Williams
+7  A: 

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,

-Oisin

x0n
or @"<a href='#' onclick=""foo('{0}','{1}')"">{2}</a>" if the backslashes look as goofy to you as they do to me.
No Refunds No Returns
I'm not a fan of the doubled-up quotes simply because it annoys resharper too much :)
x0n
+1  A: 

Replace the following line:

builder.Append((char)22);

with

builder.Append("\"");

peacmaker