3

I found in this link a solution to transfer some data from my model to a javascript object. The problem is that I have an error in visual studio indicating that the semi-colon is invalid but when I try to run my application, it works perfectly.

Here is a screenshot that show the error:

enter image description here

But if I remove the semi-colon, I now have this error:

enter image description here

In anyways, a javascript statement should always have a semi-colon at the end of the line.

What means this error if when I run my application, all works fine?

Community
  • 1
  • 1
Samuel
  • 12,073
  • 5
  • 49
  • 71
  • 2
    possible duplicate of [razor/javascript and trailing semicolon](http://stackoverflow.com/questions/12111729/razor-javascript-and-trailing-semicolon) – epascarello Nov 12 '12 at 18:32

3 Answers3

3

You might try enclosing it in a block:

var serializedData = @{ 
    Html.Raw(NewtonSoft.Json.JsonConvert.SerializeObject(Model));
};

Edit: This answer only applies to VS 2010. An upgrade in VS 2012 breaks this workaround as well.

Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
  • @crush: Actually digging into it, we are both correct, and we are both wrong. One of the deleted answers in the duplicate links to a question that explains why (http://stackoverflow.com/questions/12275095/upgrade-from-net-4-to-4-5-breaks-html-raw-call-in-javascript). When I made this answer, I was on Studio 2010 (as were most people since 2012 had only come out a few months prior), and apparently the upgrade to 2012 (and subsequently 2013) had a change in the JavaScript parser that broke this. I'll update this to reflect that nuance, but it does explain why it worked then and not now. – Joel Etherton Feb 06 '15 at 13:06
  • Removed my comments per your edit. Thanks for maintaining the validity of this site. – crush Feb 06 '15 at 13:57
2

I am just starting with Razor/MVC4, but can you so something like this?

@{
    var serializedData = Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
}
<script>
    ...
    var serializedData = @serializedData;
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 2
    Thank you epascarello but the error seem to be transfered to the semi-colon of the @serializedData variable. – Samuel Nov 12 '12 at 18:23
1

Wrap your razor code in quotes like so:

var myVar = '@serializedData';

As JavaScript duck types you should be ok in most use cases.

  • If you are placing JSON within those strings, you will need to use `JSON.parse(...)` on the string in order to deserialize it into a JavaScript object. Doing this liberally could slow down the execution of your page. A better solution would be to use an identity function. That said, this is the only working solution presented on this page. *See the duplicate question for better work-arounds.* – crush Feb 06 '15 at 00:10