0
alert("...");
var values = "value1
valu2part1 value2part2 
value3
valu4";
alert(values);

I am assigning:

var values = "<%=Model.Values%>";

These values are stored in a database. The values are entered through a textarea and in the database each line is seperated by \t\r.

When I take this to a JavaScript variable using:

var values = "<%=Model.Values%>";

I am getting some thing like:

var values = "value1
valu2part1 value2part2
value3
valu4";

But this is anerror. What can I do?

Bill the Lizard
407k213 gold badges579 silver badges892 bronze badges
asked Oct 4, 2010 at 15:27

2 Answers 2

3
var values = "<%=Model.Values%>";

This is unsafe. Not only will it fail when there are newlines in the string (as JavaScript string literals cannot span multiple lines), it's also possible for a " in the value to end the string prematurely. If the value contains user-submitted data, that's a script-injection security hole (XSS).

To create JS literal syntax use a JSON serialiser. For example with JavaScriptSerializer:

var values= <%= new JavaScriptSerializer().Serialize(Model.Values) %>;

or eg Json.NET if you're on older .NET versions.

answered Oct 4, 2010 at 15:45
Sign up to request clarification or add additional context in comments.

Comments

0

You can replace your new lines with escape sequences (\n) before outputting your string to the JS.

answered Oct 4, 2010 at 15:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.