0

I have the following Razor code :

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

                }

But when I want to use the variable "villages" in JS I get :

ReferenceError: villages is not defined

How can I do it ?

0

1 Answer 1

1

Change @villages to @Html.Raw(Json.Encode(villages));. Ignore the syntax error and run the application.

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

  }

Please check. It worked for me.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.