Upgrading from .net 4 to 4.5 breaks Html.Raw call in Javascript

I have the following code on a C # MVC 3 razor page where I pass serialized data to a javascript variable for KnockoutJs:

@{ var listData = new JavaScriptSerializer().Serialize(Model.ListItems); var pagerData = new JavaScriptSerializer().Serialize(Model.Pager); } // additional code <script type="text/javascript" > var ListData = @(Html.Raw(listData)); // <-- Syntax Error here var PagerData = @(Html.Raw(pagerData)); // <-- Syntax Error here // additional js code </script> 

After upgrading to VS 2012, I get errors in squidgles after javascript sem-colons at the end of the Html.Raw line above. The project is consistent, but VS 2012 displays a "Syntax error" in the error list for each line. Without half-columns, javascript also shows "Syntax error."

This code worked without problems in the previous version. Is this a bug in the VS 2012 parser and is there a way to avoid the generated errors?

Edit Does anyone else see this problem? Below is a simplified version with the same problem as on the new page. If you add a half-line at the end of the ListData line, you get a javascript syntax error, without which it will be on the next line. Is this a bug in the javascript compiler between VS2010 and VS2012?

 @{ var listData = "test"; var pagerData = "test2"; } <script type="text/javascript" > var ListData = @(Html.Raw(listData)) var PagerData = @(Html.Raw(pagerData)) </script> 
+4
source share
4 answers

Please add a vote on this issue. We will consider this issue in the next version of VS. I attached your resulting code to this error and added a link to this post as another manifestation of the problem.

+4
source

This issue still exists in Visual Studio 2013 SP 2

To fix this warning message, first initialize the javascript variable. IMO Visual studio thinks var as implicitly entered if any var follows @.

  var ListData; var PagerData; ListData = @(Html.Raw(listData)); PagerData = @(Html.Raw(pagerData)); 
+1
source

I use MVC5 and find the same problem, so I solved it in a way that should work in all versions

 @Html.Raw("var myData = " + Json.Encode(this.Model.MyData) + ";" ) 

However, I would use this only in the simplest situations, since you lose any kind of intellisense with respect to the type of VAR (although it treats it as a global instance, and the compiler does not throw a wobbler), so at the moment I think that the initial, empty defining is probably the best way to continue.

+1
source

I had the same thing, but this happens randomly. I tried to solve this problem as follows:

Make sure you can compile / build / debug in debug mode, switch to release mode and try to debug / publish from this mode. Return to debug mode and try publishing again.

Some combination of switching modes does the trick, I can just nail what exactly. When you earn it, do not close VS; -)

Let hope MS get this fix in SP1.

0
source

Source: https://habr.com/ru/post/1432410/


All Articles