Problems using a StringBuilder to construct HTML i

2019-08-02 01:44发布

问题:

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

回答1:

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,



回答2:

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("\""); 


回答3:

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



回答4:

Replace the following line:

builder.Append((char)22);

with

builder.Append("\"");



标签: c# html escaping