Reputation: 2135
I have the following code in a c# MVC 3 razor page where I am passing serialized data into 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 am getting error squiggles after the javascript semi-colons at the end the Html.Raw lines above. The project complies but VS 2012 displays 'Syntax Error' in the Error List for each line. Without the semi-colons the javascript also shows a 'Syntax Error'.
This code worked without issues in the previous version. Is this a bug in the VS 2012 parser and is there a way to avoid the generated errors?
Edit Anyone else seeing this issue? Below is a simplified version with the same issue isolated in a new page. If you add a semi-colon at the end of the ListData line you get a javascript syntax error, without one it is 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>
Upvotes: 4
Views: 1533
Reputation:
I'm using MVC5 and finding the same issue, so I solved it this way, which 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 intellisense as to VAR type (although it does treat it as a global instance and the compiler doesn't throw a wobbler), so for now I think an initial, empty definition is probably the best way to proceed.
Upvotes: 1
Reputation: 1359
This issue still exist in Visual Studio 2013 SP 2
To fix this warning message initialize javascript variable first. IMO Visual studio think var as implicitly typed if any var followed by @.
var ListData;
var PagerData;
ListData = @(Html.Raw(listData));
PagerData = @(Html.Raw(pagerData));
Upvotes: 1
Reputation: 691
I have had the same thing happen, but it does so at random. What I have tried to resolve it is the following:
Make sure you can compile/build/debug in Debug mode, switch to Release mode and attempt to debug/publish from that mode. Switch back to Debug mode and re-attempt the publish.
Some combination of switching modes does the trick, I just can'y nail down what it is exactly. Once you get it working, don't close VS ;-)
Let's hope MS gets this fixed in SP1.
Upvotes: 0
Reputation: 1450
Please add vote on this connect issue. We will address this issue in next version of VS. I have attached your repro code to this bug and added link to this post as another manifestation of the issue.
Upvotes: 4