简体   繁体   English

剃刀页面中的Javascript语法错误

[英]Javascript syntax error in razor page

I found in this link a solution to transfer some data from my model to a javascript object. 我在此链接中找到了将一些数据从我的模型传输到javascript对象的解决方案。 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. 问题是我在visual studio中有一个错误,表明分号是无效的,但是当我尝试运行我的应用程序时,它运行得很好。

Here is a screenshot that show the error: 以下是显示错误的屏幕截图:

在此输入图像描述

But if I remove the semi-colon, I now have this error: 但如果我删除分号,我现在有这个错误:

在此输入图像描述

In anyways, a javascript statement should always have a semi-colon at the end of the line. 无论如何,javascript语句应该总是在行尾有一个分号。

What means this error if when I run my application, all works fine? 如果我运行我的应用程序,一切正常,这意味着什么意思?

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. 编辑:此答案仅适用于VS 2010. VS 2012中的升级也会破坏此解决方法。

I am just starting with Razor/MVC4, but can you so something like this? 我刚开始使用Razor / MVC4,但你能这样吗?

@{
    var serializedData = Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
}
<script>
    ...
    var serializedData = @serializedData;

Wrap your razor code in quotes like so: 将你的剃刀代码包含在引号中,如下所示:

var myVar = '@serializedData';

As JavaScript duck types you should be ok in most use cases. 作为JavaScript duck类型,在大多数用例中你应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM