开发者

How can I pass json string into HtmlHelper's result?

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.Forma开发者_运维问答t(@"<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("\"","&quot;")

Not helping. Browser automatically converts &quot;s into ". I don't know how to preserve the markup


Is html.Encode the answer?

return new HtmlString(Html.Encode(str)); 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜