是什么导致这个mvc razor语法错误?

时间:2023-02-06 04:02:07
var openWos = @Model.MyMaintenanceDashboard.OpenWorkOrders;

Why is Visual Studio saying this is a syntax error? It runs fine, but what would the proper syntax be?

为什么Visual Studio会说这是语法错误?它运行正常,但正确的语法是什么?

Update: OpenWos is a javascript variable

更新:OpenWos是一个javascript变量

2 个解决方案

#1


0  

If this is a javascript code, then you need to quote it so that you do not get the 'syntax' error.

如果这是一个javascript代码,那么您需要引用它,以便您不会收到“语法”错误。

var openWos = '@Model.MyMaintenanceDashboard.OpenWorkOrders';

#2


0  

If you're setting a C# var, the correct syntax would be without the @ in front of Model as you're already in a C# code block:

如果你正在设置一个C#var,那么正确的语法就是没有模型前面的@,因为你已经在C#代码块中了:

@{
    var openWos = Model.MyMaintenanceDashboard.OpenWorkOrders;
}

Edit:

You've clarified that this is a JavaScript variable. There shouldn't be a syntax error at all, as this is valid Razor. There is a distinct difference between quoting the value as suggested by Stephen, and the code that you posted originally. The type of the JavaScript variable is a string when quoted instead of a number.

您已经澄清这是一个JavaScript变量。根本不应该有语法错误,因为这是有效的Razor。引用Stephen建议的值与您最初发布的代码之间存在明显差异。 JavaScript变量的类型是引用而不是数字时的字符串。

For example, including this in a page:

例如,在页面中包含此内容:

<script>
    @{ int z = 10; }

    var x = @z;
    console.log(x);
    console.log(typeof x);

    var y = '@z';
    console.log(y);
    console.log(typeof y);
</script>

Results in the following being logged to the console:

以下结果记录到控制台:

10
number
10
string

And there is no syntax error reported using the variable @z in either instance.

并且在任一实例中都没有使用变量@z报告语法错误。

#1


0  

If this is a javascript code, then you need to quote it so that you do not get the 'syntax' error.

如果这是一个javascript代码,那么您需要引用它,以便您不会收到“语法”错误。

var openWos = '@Model.MyMaintenanceDashboard.OpenWorkOrders';

#2


0  

If you're setting a C# var, the correct syntax would be without the @ in front of Model as you're already in a C# code block:

如果你正在设置一个C#var,那么正确的语法就是没有模型前面的@,因为你已经在C#代码块中了:

@{
    var openWos = Model.MyMaintenanceDashboard.OpenWorkOrders;
}

Edit:

You've clarified that this is a JavaScript variable. There shouldn't be a syntax error at all, as this is valid Razor. There is a distinct difference between quoting the value as suggested by Stephen, and the code that you posted originally. The type of the JavaScript variable is a string when quoted instead of a number.

您已经澄清这是一个JavaScript变量。根本不应该有语法错误,因为这是有效的Razor。引用Stephen建议的值与您最初发布的代码之间存在明显差异。 JavaScript变量的类型是引用而不是数字时的字符串。

For example, including this in a page:

例如,在页面中包含此内容:

<script>
    @{ int z = 10; }

    var x = @z;
    console.log(x);
    console.log(typeof x);

    var y = '@z';
    console.log(y);
    console.log(typeof y);
</script>

Results in the following being logged to the console:

以下结果记录到控制台:

10
number
10
string

And there is no syntax error reported using the variable @z in either instance.

并且在任一实例中都没有使用变量@z报告语法错误。