Domi
Domi

Reputation: 1389

Pass an Razor List to Javascript (JSON)

Im tring to pass a in razor view declared list into a javascript var:

  List<testObj> mylist= new List<testObj>();

    <div class="listboxFilterItem" onclick=' setList(@(Html.Raw(Json.Serialize(mylist))))'> <div style="padding-top:2px; float: left;">Test</div>     <div class="listboxChosenFilter">*</div>   </div>

My javascript code looks like this :

function setList(list) {
    var jsonObj = JSON.parse(list);
    console.log(jsonObj);

  }


</script>

But I get ILLEGAL token exception because of my quotes --> "data"<-- .

How do u pass in razor view declared lists to a javascript function?

Upvotes: 1

Views: 4301

Answers (4)

Vladyslav Dubovyi
Vladyslav Dubovyi

Reputation: 46

Worked for me

onclick="setList('@Json.Serialize(mylist).ToString()'))"

Upvotes: 0

Dima Pavlenko
Dima Pavlenko

Reputation: 161

I had a strongly typed Razor cshtml view of a model with a property ICollection<Options>. I was looking for how to pass lists/lists of lists/list of objects into JavaScript, and saw "don't use @Html.Raw()" in some places for security reasons.

What worked for me in .NET Core 3.1, was using only @Json.Serialize() of the System.Text.Json namespace. So in my case I used it as a JavaScript variable value:

var myModelOptionsList = @Json.Serialize(Model.Options);

and now I have a list of JavaScript objects.

Note: The project used EntityFramework Core to store the model (and its Options). Each Option object had a reference navigation property back to the parent model. This caused a JSON Self Referencing Loop Exceptions during serialization. The easiest solution was to not include these references during serialization, using [JsonIgnore] attribute over the model reference navigation property of the Option object.

Upvotes: 0

Baqer Naqvi
Baqer Naqvi

Reputation: 6504

Try replacing onclick code.

Replace

 onclick=' setList(@(Html.Raw(Json.Serialize(mylist))))'

With

onclick='setList(@Html.Raw(Json.Encode(mylist)))'

Upvotes: 4

Frank Witte
Frank Witte

Reputation: 466

I am not sure which MVC/.NET version you are using, but have you tried using JavaScriptSerializer instead of Json?

@{
    var myList = new List<testObj>();
    var list = new JavaScriptSerializer().Serialize(myList);
    // list now contains a JSON string repesentation of myList.
}

<script>
   var options = @Html.Raw(list);
</script>

The options javascript variable should then contain an array of whatever items are in the myList C# variable.

Upvotes: 1

Related Questions