In my MVC view am having the below piece of code
<script type="text/javascript">
@foreach (var item in Model.Test)
{
<text> jsFunction(@item.someValue); </text>
}
</script>
Where am calling the Javascript function based on the data i get from model dynamically.
For Example At run time it is rendered like below based on the model data
jsFunction("Works Fine");
jsFunction("works Fine");
Which correctly calls my javascript function
But in case of a new line getting "unterminated string literal" because of the new line
jsFunction("not working
with new line");
What is the best way to handle this Scenario
Thanks
What is the best way to handle this Scenario
Use a JSON serializer which will ensure that the value passed to your javascript function is properly escaped:
<script type="text/javascript">
@foreach (var item in Model.Test)
{
<text>jsFunction(@Html.Raw(Json.Encode(item.someValue)));</text>
}
</script>
or if you update your jsFunction
to take an array instead of a single item you could do this:
<script type="text/javascript">
var values = @Html.Raw(Json.Encode(Model.Test));
jsFunction(values);
</script>
and then loop through the normal javascript array that will be passed to your function.
P.S: Don't worry if Razor Intellisense is putting a red squiggle around this code. Visual Studio Intellisense in Razor views doesn't work well. Just ignore the warning and run your application and observe the properly generated code.
Simplest solution is to create a helper or something:
@* declared at top of razor page *@
@helper jsFunction(String str)
{
str = (str ?? String.Empty).Trim().Replace(Environment.NewLine, "\\n");
@:jsFunction("@Html.Raw(str)");
}
@* example usage *@
foreach (var item in Model.Test)
{
@jsFunction(@item.Comment)
}
That would perform sanitization on the string to make it convert \n
in to the JavaScript counter-part \\n
. You may also include exceptions for quotation marks (turn "
into \"
, etc.)
The better alternative is to use something like JSON.NET though:
<text>jsFunction(@Html.Raw(JsonConvert.Serialize(@item.Comment)))</text>
That would make it completely safe to JavaScript (and handle the exceptions for you).
try this
jsFunction(@Html.Raw(Json.Encode(item.Comment)))
I think this should solve your issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With