Sunny Drall
Sunny Drall

Reputation: 914

Storing html into a JS variable

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.

Upvotes: 1

Views: 694

Answers (2)

K D
K D

Reputation: 5989

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

Upvotes: 1

AKX
AKX

Reputation: 168863

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.

Upvotes: 0

Related Questions