Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - Handling unterminated string literal for new line

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

like image 948
user2067567 Avatar asked Oct 17 '13 11:10

user2067567


3 Answers

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.

like image 101
Darin Dimitrov Avatar answered Nov 02 '22 23:11

Darin Dimitrov


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).

like image 20
Brad Christie Avatar answered Nov 02 '22 23:11

Brad Christie


try this

jsFunction(@Html.Raw(Json.Encode(item.Comment)))

I think this should solve your issue.

like image 37
Anto Subash Avatar answered Nov 03 '22 00:11

Anto Subash