如何将 json 字符串传递到 HtmlHelper 的结果中?
我想传递一个序列化的 json 对象并在自定义 Html Helper 的结果中返回它。像这样的东西
public static HtmlString SomeHelper(this HTMLHelper htmlHelper)
{
var MyObject = new Foo();
var oSerializer = new JavaScriptSerializer();
var str = string.Format(@"<a href""#""
onclick=""var myObject = $.parseJSON(0);
alert('my object name property '+ myObject.Name); ""> Click me</a>",
oSerializer.Serialize(MyObject));
return new HtmlString(str);
}
理论上应该有效,但事实并非如此。它将序列化字符串放入标记中,然后由于双引号和单引号,一切都变得混乱。我尝试在序列化后应用 HtmlString,我什至尝试使用 HTmlString.ToHtmlString()。什么都不起作用。
事实上我可能不应该这样做。单击事件调用应该不引人注目地使用。我知道。然后我仍然必须将 json 对象保存在生成的标记中的某个位置。
更新:我什至尝试这样做:
sJson.replace("\"",""")
没有帮助。浏览器自动将 "
转换为 "
。我不知道如何保留标记
I want to pass a serialized json object and returned it within custom Html Helper's result. Something like this
public static HtmlString SomeHelper(this HTMLHelper htmlHelper)
{
var MyObject = new Foo();
var oSerializer = new JavaScriptSerializer();
var str = string.Format(@"<a href""#""
onclick=""var myObject = $.parseJSON(0);
alert('my object name property '+ myObject.Name); ""> Click me</a>",
oSerializer.Serialize(MyObject));
return new HtmlString(str);
}
That thing theoretically should work, but it doesn't. It puts serialized string to markup and then everything gets messy, because of double and single quotes. I tried to apply HtmlString after serialization, I even tried to use HTmlString.ToHtmlString(). Nothing works.
In fact I probably shouldn't do that. The click event call should be used unobtrusively. I know. Then I still have to save json object somewhere in the resulting markup.
Upd: I even tried to do that:
sJson.replace("\"",""")
Not helping. Browser automatically converts "
s into "
. I don't know how to preserve the markup
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
html.Encode 是答案吗?
Is html.Encode the answer?
我想唯一的解决方案是将 oSerializer.Serialize(MyObject)) 中的所有双引号替换为其他符号,这不会在 html 标记中冲突,然后在解析之前将双引号放回去,否则就不会一个合法的 json 字符串。
I guess the only solution would be to replace all double quotes in oSerializer.Serialize(MyObject)) with some other symbol, which wouldn't conflict in html markup, and then before the parsing put double quotes back, otherwise it wouldn't be a legit json string.