Problems using a StringBuilder to construct HTML in C#

时光怂恿深爱的人放手 提交于 2020-01-06 02:00:54

问题


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



来源:https://stackoverflow.com/questions/1970940/problems-using-a-stringbuilder-to-construct-html-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!