c# 如何格式化字符串以用于 HTML 属性?

c# How to format string for use in HTML attribute?

我想知道是否有任何 c# 库可以轻松格式化要在 onclick html 属性 属性 中使用的字符串。

我正在使用 c# 动态生成一个 html 页面,并且正在为某些 onclick 事件动态生成 javascript。我想确保 &"\ ... 等字符不会导致 html 中断或被忽略。例如,在下面的示例中,我想显示警报消息 h\m,除非我创建单独的逻辑来处理 \ 和 &:

,否则我将无法这样做

function method1(inputValue){
  alert(inputValue);
  }
<input type="button" value="button1" onclick="method1('h\&#3m')"/>

您可能想要查看 HttpServerUtility 的 HtmlEncode 方法。 https://msdn.microsoft.com/en-us/library/w3te6wfz(v=vs.110).aspx