iLemming
iLemming

Reputation: 36166

HowTo pass List<T> object to Javascript in MVC?

I wanna do something like that:

 $(document).ready(function () 
{
    calendarGrid.create(@Model.Events)
}

Model.Events is a List.

I tried to use:

nothing helps.

Upvotes: 3

Views: 5566

Answers (2)

marcind
marcind

Reputation: 53183

You need to write code that will serialize your server-side list into code that gets sent to the client. Trye something like this:

calendarGrid.Create(@Html.Raw(JavaScriptSerializer.Serialize(Model.Events)))

The entire contents of @Html.Raw(...) will be emitted to the output.

Upvotes: 3

vt100
vt100

Reputation: 796

I've had great success by setting a javascript variable to it, using:

<script>
     var eventList = @(Html.Raw(Json.Encode(Model.Events)));

     $(document).ready(function () {
        calendarGrid.create(eventList);
     });

</script>

From there, you can freely use the eventList variable as a JSON object.

The Trick is the use of Html.Raw to prevent any further encoding from happening

Upvotes: 2

Related Questions