This question already has answers here:
Pass Array from MVC to javascript?
                            
                                (9个答案)
                            
                    
                3年前关闭。
        

    

我有以下剃刀代码:

               @{
                    var villages = (List<string>)  @ViewData["allVillages"];
                }
               @if (villages != null)
                {
                    <script type="text/javascript">
                        var villages = @villages;
                    </script>

                }


但是当我想在JS中使用变量“ villages”时,我得到:


  ReferenceError:未定义村庄


我该怎么做 ?

最佳答案

将@villages更改为@ Html.Raw(Json.Encode(villages));。忽略语法错误,然后运行应用程序。

 @{
    var villages = (List<string>)@ViewData["allVillages"];
  }
 @if (villages != null)
  {
    <script type="text/javascript">
    var villages =  @Html.Raw(Json.Encode(villages));
    </script>

  }


请检查。它为我工作。

09-17 11:04