最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Store Html.Raw() in a string in Javascript, ASP.NET MVC 3 - Stack Overflow

programmeradmin1浏览0评论

I'm using ASP.NET and I have a string of HTML in the database.

I want to get that html into a variable on the client.

If I do this:

var x = '@Html.Raw(myModel.FishValue)'

it works fine, because it's essentially doing

var x = '<p>hello!</p>';

however if there are quotes in the html it breaks the page.

My initial guess would be to .Replace the raw string to add escapes to the quotes, however both .ToString() and .ToHtmlString() (as Html.Raw returns an IHtmlString) do not produce the same markup as simple Html.Raw().

So I'm at a loss of what best to do.

I'm using ASP.NET and I have a string of HTML in the database.

I want to get that html into a variable on the client.

If I do this:

var x = '@Html.Raw(myModel.FishValue)'

it works fine, because it's essentially doing

var x = '<p>hello!</p>';

however if there are quotes in the html it breaks the page.

My initial guess would be to .Replace the raw string to add escapes to the quotes, however both .ToString() and .ToHtmlString() (as Html.Raw returns an IHtmlString) do not produce the same markup as simple Html.Raw().

So I'm at a loss of what best to do.

Share Improve this question asked Apr 4, 2012 at 16:14 NibblyPigNibblyPig 52.9k75 gold badges217 silver badges378 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 10

What about replacing before calling the Html.Rawmethod?

 var x = '@Html.Raw(myModel.FishValue.Replace("'","\\'"))' 

UPDATE:

There might be other escape chars in the string coming from the model. For that reason I would recommend replacing the slashes first as well. Of course it all depends on what might come from the server in your model.

 var x = '@Html.Raw(myModel.FishValue.Replace("\\","\\\\'").Replace("'","\\'"))' 

A sample snippet representing the behavior in the javascript:

//Let's say my Model Content is >  I'd Say \ is a escape character. You can't "Escape"  
    // YOu would have to replace ' --> \' and \ --> \\
    var stringFromServer = 'I\'d Say \\ is a escape character. You can\'t "Escape"'
    alert(stringFromServer)

Try this:

var x = '@(System.Web.HttpUtility.HtmlEncode(myModel.FishValue))';

If you need to decode the HTML on the client side use

unescape(x)

I think JQuery (not sure if you're using it or not) handles encoded HTML strings so you might not need unescape().

Try out the anti-xss library from Microsoft (which will be included I believe by default in asp.net 4.5):

 AntiXss.JavascriptEncode(yourContent)

Anti-Xss is available 4.1 beta. If you want to use it in your application which I highly recommend, check out: http://weblogs.asp.net/jgalloway/archive/2011/04/28/using-antixss-4-1-beta-as-the-default-encoder-in-asp-net.aspx

发布评论

评论列表(0)

  1. 暂无评论