1

I'm trying to save html into a JS variable

var popupBody = '<%= MyContext.Current.DynamicProperties.FirstOrDefault(p => p.PropertyName == "PopupModalBody").PropertyValue %>';

Above code will try to store html returned by C# to a JS variable (popupBody) but it returns Syntax Error in the console because the html is not in a single line. How can I achieve this? Thanks for any help.

3
  • I am not sure but I think you can append Replace function and use likePropertyValue.Replace("\r\n","") Commented Jan 26, 2017 at 10:52
  • 1
    try to use template string developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 26, 2017 at 10:53
  • 1
    Thanks @KD, you saved my day. Commented Jan 26, 2017 at 11:14

2 Answers 2

1

You can use template string instead of this. It is part of ES6 and make sure your browser supports this.

var popupBody = `<%= MyContext.Current.DynamicProperties.FirstOrDefault(p => p.PropertyName == "PopupModalBody").PropertyValue %>`;

Reference

Sign up to request clarification or add additional context in comments.

2 Comments

Could you suggest any other approach? because as you know this trick has problems with older browsers.
a simplest way of doing this would be... adding this value to a <div style="display:none" id="htmlContent">. then using document.getElementById("htmlContent").innerHTML access this content in your variable and use it further. as you can also destroy the DIV after this. One more way would be to replace all \n\r with empty string while assignment
0

I'm not an ASP.net (assuming that's the case from the <%= %>) programmer, but the general idea, no matter which templating or programming language you're generating JavaScript in is that you can use JSON encoding for JavaScript literals.

So -- assuming there's something like Json.Encode available in the template:

var popupBody = <%= Json.Encode(MyContext.Current.DynamicProperties.FirstOrDefault(p => p.PropertyName == "PopupModalBody").PropertyValue) %>;

Note the lack of quotes; the JSON encoder will add those, as it's encoding a string.

1 Comment

For others, I tried using the similar approach and it worked for me, try this JSON.ToJSON()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.