2016-11-27 78 views
0

定義JS變量,我有以下剃刀代碼:如何使用剃刀

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

       } 

但是,當我想使用JS變量「村莊」我得到:

ReferenceError: villages is not defined

哪有我這麼做?

回答

0

將@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> 

    } 

請檢查。它爲我工作。